- Home /
i want my CountDownTimer to stop when it reaches 00:00:00
HI Everyone
so i have this code which basically counts down my problem is that i want it to stop when it reaches 00:00:00
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");
}
}
}
Comment
Best Answer
Answer by Hellium · Mar 20, 2020 at 11:04 AM
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;
}
}
Your answer
Follow this Question
Related Questions
Create a countdown in C# (inside Coroutine) 2 Answers
Calling methods 0 Answers
Start timer with trigger 1 Answer
How to stop the countdown timer when I have collected all the coins? 2 Answers