Unity:CountDownTimer 达到 00:00:00 时停止

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

所以我有这段代码,它基本上是一个倒数计时器,我的问题是我希望它在达到 00:00:00 时停止。

目前码到00:00:00时,秒数又从00:00:59开始计时,希望有大佬帮帮我。

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");
         }
     }
 }

我用协程和TimeSpan(伪代码)重写了它:

private IEnumerator Countdown(int totalSeconds)
{
   while (totalSeconds > 0)
   {
     var time = TimeSpan.FromSeconds(totalSeconds);
     timerText.text = $"{time.Hours}:{time.Minutes}:{time.Seconds}";
     yield return new WaitForSeconds(1);
     totalSeconds--;
   }

   Debug.Log("Game over");
}

这是重置计时器的部分。

 if (secondsCount <= 0)
     {
         if(minuteCount > 0)
         minuteCount--;

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

     }

如果你想让你的计时器固定在 0,只需说

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

如果您不想重新开始,您可以删除行

secondsCount = 60; 

或者您可以添加一个记录时钟状态的布尔值。

bool timeIsOver = false;

然后在秒数到时触发它。

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

我找到了另一个答案,并认为它可能对路过的人有所帮助

public Text timerText;
 [SerializeField, Range(0, 59)] private int seconds;
 [SerializeField, Range(0, 59)] private int minutes;
 [SerializeField, Range(0, 23)] private int hours;
 private float timer;
 private void Start()
 {
     timer = hours * 3600f + minutes * 60 + seconds;
 }
 void Update()
 {
     UpdateTimerUI();
 }
 //call this on update
 public void UpdateTimerUI()
 {
     timer = Mathf.Max(timer - Time.deltaTime, 0);
     hours = Mathf.FloorToInt(timer / 3600);
     minutes = Mathf.FloorToInt((timer - hours * 3600) / 60);
     seconds = Mathf.FloorToInt(timer - hours * 3600 - minutes * 60);
     timerText.text = string.Format("{0:00}h:{1:00}m:{2:00}s", hours, minutes, seconds);
     if (timer <= Mathf.Epsilon)
     {
         Debug.Log("gameOver");
         enabled = false;
     }
 }