maxhacker11

Timer.cs

Sep 8th, 2023
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | Source Code | 0 0
  1. using System;
  2. using UnityEngine;
  3. using TMPro;
  4.  
  5. public class Timer : MonoBehaviour
  6. {
  7.     [SerializeField] private TextMeshProUGUI timerText;
  8.     [SerializeField] private float countdownValue = 60f;
  9.    
  10.     DateTime targetTime;
  11.     double currentTime;
  12.     bool active = false;
  13.  
  14.     private void Start()
  15.     {
  16.         // If the timer was started, load the value
  17.         if(PlayerPrefs.HasKey("targetTime"))
  18.         {
  19.             targetTime = DateTime.Parse(PlayerPrefs.GetString("targetTime"));
  20.             active = true;
  21.         }
  22.     }
  23.  
  24.     public void StartTimer()
  25.     {
  26.         // Calculate when the timer will elapse by adding the countdownValue to the current time, to get the targetTime
  27.         targetTime = DateTime.Now.Add(TimeSpan.FromSeconds(countdownValue));
  28.         PlayerPrefs.SetString("targetTime", targetTime.ToString());
  29.         active = true;
  30.     }
  31.  
  32.     public void StopTimer()
  33.     {
  34.         currentTime = 0f;
  35.         active = false;
  36.     }
  37.  
  38.     // Update is called once per frame
  39.     void Update()
  40.     {
  41.         // This is just a simple way to start the timer initially
  42.         if (Input.GetKeyDown(KeyCode.Y))
  43.         {
  44.             StartTimer();
  45.         }
  46.  
  47.         // If the timer is not active, don't update it anymore
  48.         if (!active)
  49.             return;
  50.  
  51.         currentTime = (targetTime - DateTime.Now).TotalSeconds;
  52.  
  53.         if (currentTime <= 0)
  54.         {
  55.             StopTimer();
  56.         }
  57.  
  58.         TimeSpan t = TimeSpan.FromSeconds(currentTime);
  59.         timerText.text = t.ToString(@"mm\:ss");
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment