- Home /
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?
Don't you want:
int $$anonymous$$s = (int)(timer / 60.0f); int seconds = (int)(timer % 60.0f);
As an aside, for performance you probably want to make sure you only run this code section(except timer -= Time.deltaTime) once every second.
This is the same as my code, isn't it? I think it doesn't matter if you add these brackets or not. The timer is still not working ;/ Thanks for reply
Ah sorry, forgot the last line; text.text = $$anonymous$$s.ToString() + ":" + seconds.ToString();
But no, those two lines are not exactly what you're doing. You are converting timer to an int, then dividing by a float, then converting back to int. In fact, my solution is bad too. Best just remove your .0f ins$$anonymous$$d, so it just does a simple int division/modulus ins$$anonymous$$d of the more expensive float version.
Answer by m0guz · Sep 16, 2016 at 05:02 PM
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);
}
Quite interesting. I think the last time did the job ;] Thanks so much.
Answer by NerdClown · Sep 16, 2016 at 05:10 PM
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 :)
This works for getting the string version of the time:
Debug.Log(string.Format("[{0}:{1}]",mins, seconds ));
Changing string formatting solved the problem. Thanks for your reply!
Your answer
Follow this Question
Related Questions
countdown timer acivation 1 Answer
C# countdown timer 9 Answers
Timer counting UP instead of DOWN 1 Answer
Why does my MatchTime Class not work when using Properties? 1 Answer