Timer shown is -1:59

The timer shown is negative. Why?

``````if (myTimer > 0)
{
myTimer -= Time.deltaTime;
int minutes = Mathf.FloorToInt (myTimer / 60f);
int seconds = Mathf.FloorToInt (myTimer - minutes * 60);

string niceTime = string.Format ("{0:0}:{1:00}", minutes, seconds);
timeLabel.text = niceTime;
}

else if (myTimer <= 0)
{
string niceTime = string.Format ("{0:0}:{1:00}", 0, 0);
//pause the game
Time. timeScale = 0.0f;

}
``````

Screenshot,

Consider the scenario where:

``````myTimer = 0.01
Time.deltaTime = 0.02 // Just over 16.6 ms (60 FPS).
``````

In this case myTimer (0.01) is > 0 so we fall into the first branch:

``````if (myTimer > 0)
{
myTimer -= Time.deltaTime;
int minutes = Mathf.FloorToInt (myTimer / 60f);
int seconds = Mathf.FloorToInt (myTimer - minutes * 60);

string niceTime = string.Format ("{0:0}:{1:00}", minutes, seconds);
timeLabel.text = niceTime;
}
``````

myTimer becomes -0.01 (after subtracting Time.deltaTime). Then minutes gets assigned (-1) and seconds gets assigned (59). So the formatted timer gets assigned -1:59! This can be fixed pretty easily by moving the decrement of myTimer outside the if statement:

``````myTimer -= Time.deltaTime;
if (myTimer > 0)
{
int minutes = Mathf.FloorToInt (myTimer / 60f);
int seconds = Mathf.FloorToInt (myTimer - minutes * 60);

string niceTime = string.Format ("{0:0}:{1:00}", minutes, seconds);
timeLabel.text = niceTime;
}
``````

That should fix the issue where we ever set the formatted time to -1:59. There’s a minor bug in the other branch of this code that you might also want to address, though. You calculate the formatted text in the second branch, but you don’t ever assign it to the text label!

``````else if (myTimer <= 0)
{
string niceTime = string.Format ("{0:0}:{1:00}", 0, 0);
timeLabel.text = niceTime; // Make sure we assign the 0:00 to the timeLabel!

// pause the game
Time. timeScale = 0.0f;
}
``````

Putting it all together:

``````myTimer -= Time.deltaTime;
if (myTimer > 0)
{
int minutes = Mathf.FloorToInt (myTimer / 60f);
int seconds = Mathf.FloorToInt (myTimer - minutes * 60);

string niceTime = string.Format ("{0:0}:{1:00}", minutes, seconds);
timeLabel.text = niceTime;
}
else if (myTimer <= 0)
{
string niceTime = string.Format ("{0:0}:{1:00}", 0, 0);
timeLabel.text = niceTime;

// pause the game
Time. timeScale = 0.0f;
}
``````