Search code examples
unity-game-engineuser-interfacetimercountdown

Unity: CountDownTimer to stop when it reaches 00:00:00


so i have this code which is basically a count down timer, my problem is that i want it to stop when it reaches 00:00:00.

currently when the code reaches 00:00:00, the seconds starts to count again from 00:00:59, so i hope if there is any one who can help me.

public class CountDownTimer : MonoBehaviour
 {
     public Text timerText;
     public float secondsCount;
     public int minuteCount;
     public int hourCount;
     void Update()
     {
         UpdateTimerUI();
     }
     //call this on update
     public void UpdateTimerUI()
     {
         //set timer UI
         if(secondsCount > 0)
         secondsCount -= Time.deltaTime;
         timerText.text = hourCount + "h:" + minuteCount + "m:" + (int)secondsCount + "s";
         if (secondsCount <= 0)
         {
             if(minuteCount > 0)
             minuteCount--;

             //if(minuteCount!= 0)
             secondsCount = 60;

         }

         else if (minuteCount <= 0)
         {
             if(hourCount > 0)
             hourCount--;

             if(hourCount != 0)
             minuteCount = 60;
         }

          if (secondsCount <= 0 && minuteCount <= 0 && hourCount <= 0)
         {
             Debug.Log("gameOver");
         }
     }
 }

Solution

  • This is the part that is resetting your timer.

     if (secondsCount <= 0)
         {
             if(minuteCount > 0)
             minuteCount--;
    
             //if(minuteCount!= 0)
             secondsCount = 60;
    
         }
    

    If you want your timer to clamp at 0 just say

    if(secondsCount <=){
        secondsCount = 0;
    }
    

    If you dont want it to start over you can just remove the line

    secondsCount = 60; 
    

    or you could add a bool that records the state of your clock.

    bool timeIsOver = false;
    

    and then trigger it when the seconds are up.

    if(timeIsOver == false){
    secondsCount -= Time.deltaTime;
    }
    if(secondsCount <= 0  ){
       timeIsOver = true;
    }