I wrote a simple countdown timer for my game. Please have a look on it:
void Update()
{
timer -= Time.deltaTime;
int mins = (int)timer / 60.0f;
int seconds = (int)timer % 60.0f;
text.text = timer.ToString (mins.ToString() + ':' + seconds.ToString()); // Text is a reference to UI Text object
}
At start I set it to 2 mins (120 seconds). Everything works fine until the timer reach 1:50 - then it displays 1:5110 instead of 1:50. I really don’t know why this happens. I tried to add the following line to the script:
text.text = text.text.Substring(0,4);
But after doing it timer was just avoiding 1:50. There was a 2 second long break between 1:51 and 1:49 .
The problem happens every 10 seconds. Can you help me?
This is my code, works fine for me. I used FixedUpdate, you don’t have to run timer on every frame. Your problem most likely caused by “60.0f” float numbers. Try adding Mathf.Floor(timer % 60.0f)