Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using UnityEngine;
- using TMPro;
- public class Timer : MonoBehaviour
- {
- [SerializeField] private TextMeshProUGUI timerText;
- [SerializeField] private float countdownValue = 60f;
- DateTime targetTime;
- double currentTime;
- bool active = false;
- private void Start()
- {
- // If the timer was started, load the value
- if(PlayerPrefs.HasKey("targetTime"))
- {
- targetTime = DateTime.Parse(PlayerPrefs.GetString("targetTime"));
- active = true;
- }
- }
- public void StartTimer()
- {
- // Calculate when the timer will elapse by adding the countdownValue to the current time, to get the targetTime
- targetTime = DateTime.Now.Add(TimeSpan.FromSeconds(countdownValue));
- PlayerPrefs.SetString("targetTime", targetTime.ToString());
- active = true;
- }
- public void StopTimer()
- {
- currentTime = 0f;
- active = false;
- }
- // Update is called once per frame
- void Update()
- {
- // This is just a simple way to start the timer initially
- if (Input.GetKeyDown(KeyCode.Y))
- {
- StartTimer();
- }
- // If the timer is not active, don't update it anymore
- if (!active)
- return;
- currentTime = (targetTime - DateTime.Now).TotalSeconds;
- if (currentTime <= 0)
- {
- StopTimer();
- }
- TimeSpan t = TimeSpan.FromSeconds(currentTime);
- timerText.text = t.ToString(@"mm\:ss");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment