Advertisement
Guest User

timer.cs

a guest
Apr 6th, 2020
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using TMPro;
  5.  
  6. public class timer : MonoBehaviour
  7. {
  8.     // start time value
  9.     [SerializeField] float startTime;
  10.  
  11.     // current Time
  12.     float currentTime;
  13.  
  14.     // whether the timer started?
  15.     bool timerStarted = false;
  16.  
  17.     // ref var for my TMP text component
  18.     [SerializeField] TMP_Text timerText;
  19.  
  20.     // Start is called before the first frame update
  21.     void Start()
  22.     {
  23.         //resets the currentTime to the start Time
  24.         currentTime = startTime;
  25.         //displays the UI with the currentTime
  26.         timerText.text = currentTime.ToString();
  27.         // starts the time -- comment this out if you don't want to automagically start
  28.         timerStarted = true;
  29.     }
  30.  
  31.     // Update is called once per frame
  32.     void Update()
  33.     {
  34.         // you are starting the timer at "Start", you can still use the A-button to restart it.
  35.         if (Input.GetKeyDown(KeyCode.A))
  36.         {
  37.             currentTime = startTime;
  38.             timerStarted = true;
  39.         }
  40.  
  41.         if (timerStarted)
  42.         {
  43.             // subtracting the previous frame's duration
  44.             currentTime -= Time.deltaTime;
  45.             // logic current reached 0?
  46.             if(currentTime <= 0)
  47.             {
  48.                 Debug.Log("timer reached zero");
  49.                 timerStarted = false;
  50.                 currentTime = 0;
  51.             }
  52.  
  53.             timerText.text = currentTime.ToString("f1");
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement