Search Unity

Timer Countdown

Discussion in 'Scripting' started by rudigreig, Jun 16, 2019.

  1. rudigreig

    rudigreig

    Joined:
    Dec 11, 2018
    Posts:
    50
    I've looked for a simple method of doing this before but never found anything that works for me. Can anyone help me write a script for a timer that counts down (and is shown on UI as text) and when it reaches 0 it goes Scene Build +1? Please give me a quick and easy solution (preferably a script)
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    rudigreig likes this.
  3. lumoconnor

    lumoconnor

    Joined:
    Jan 17, 2016
    Posts:
    27
    You could also consider using Coroutines. They make it very straightforward to implement this kind of behaviour once you get the hang of them.

    Example:

    Code (CSharp):
    1. Text timerText;
    2.  
    3. void StartTimer()
    4. {
    5.     StartCoroutine("Timer", 10);
    6. }
    7.  
    8. IEnumerator Timer(int startTime)
    9. {
    10.     int time = startTime;
    11.    
    12.     while(time > 0)
    13.     {
    14.         time = time - 1;
    15.         timerText.text = time.ToString();
    16.         yield return new WaitForSeconds(1.0);
    17.     }
    18.  
    19.     // Load next scene etc...
    20. }
     
    rudigreig likes this.
  4. ZaffreSheep

    ZaffreSheep

    Joined:
    Aug 26, 2018
    Posts:
    32
    I had to code a UI timer for my most recent game, here's the way I did it.

    There's a float I have, named TotalSeconds, and this variable decreases by Time.deltatime in the Update() function.
    After this, I make 2 local variables, a minutes, and a seconds. Since TotalSeconds is in seconds, we can set Minutes to TotalSeconds/60, and we can set the seconds to TotalSeconds % 60. That returns the remainder after dividing the total seconds by 60.
    Doing these 2 assignments will convert any amount of seconds you put in into a minute variable and a second variable.
    You can simply combine them in a string then!

    Code (CSharp):
    1. //I used Mathf.FloorToInt to ensure I don't get any weird numbers
    2. min = Mathf.FloorToInt (totalSeconds / 60);
    3. sec = Mathf.FloorToInt (totalSeconds % 60);
     
    rudigreig likes this.
  5. rudigreig

    rudigreig

    Joined:
    Dec 11, 2018
    Posts:
    50
    thanks for the answer!