Advertisement
Guest User

timer.cs

a guest
Apr 6th, 2020
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.19 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.         currentTime = startTime;
  24.         timerText.text = currentTime.ToString();
  25.         timerStarted = true;
  26.     }
  27.  
  28.     // Update is called once per frame
  29.     void Update()
  30.     {
  31.         if (Input.GetKeyDown(KeyCode.A))
  32.         {
  33.             timerStarted = true;
  34.         }
  35.  
  36.         if (timerStarted)
  37.         {
  38.             // subtracting the previous frame's duration
  39.             currentTime -= Time.deltaTime;
  40.             // logic current reached 0?
  41.             if(currentTime <= 0)
  42.             {
  43.                 Debug.Log("timer reached zero");
  44.                 timerStarted = false;
  45.                 currentTime = 0;
  46.             }
  47.  
  48.             timerText.text = currentTime.ToString("f1");
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement