Timer doesn't work properly

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?

You had me stumped dude!

Added this debug line, and it was never triggered, even if the numbers kept being weird:

  if (seconds > 60)
  {
      Debug.Log("MEH UNEXPECTED FAIL! timer: " + timer + " as int: " + ((int)timer) + " timer mod 60: " + ((int)timer) % 60 + " seconds: " + seconds);
  }

So it turned out it was the formatting of the string that I hadn’t even bothered looking twice at :slight_smile:

This works for getting the string version of the time:

Debug.Log(string.Format("[{0}:{1}]",mins, seconds ));

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)

    void FixedUpdate()
    {
        timePassed += Time.deltaTime;
        float timeLeft = maxTime - timePassed;

        string min = Mathf.Floor(timeLeft / 60).ToString("00");
        string sec = Mathf.Floor(timeLeft % 60).ToString("00");

        timeString.text = string.Format("{0}:{1}", min, sec);
    }