Game Over Text When Timer Ends

Hi,
I made a very simple timer, and it stops at 0:0, but I want it to display “Game Over” when it hits that point. It stays at 0:0. How can I fix this?

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour {

public Text timerText;
float minutes = 1;
float seconds = 0;
private float startTime;

void Start () {
	startTime = Time.time;
}

void Update () {

	if (seconds == 0) {
		minutes--;
		seconds = 59;
		timerText.text = minutes.ToString () + ":" + seconds.ToString ("f0");
		Debug.Log (minutes + " " + seconds);
	} else if (seconds > 0) {
		seconds -= Time.deltaTime;
		timerText.text = minutes.ToString () + ":" + seconds.ToString ("f0");
		Debug.Log (minutes + " " + seconds);
	} 
	else if (minutes == 0 && seconds == 0) {
		timerText.text = "Game Over";
		Debug.Log ("go");

	}

}

}

Hello there,

I would not recommend using the operator “==” to compare floats, as they are not precise like integers.
Instead, your ‘else if’ statement should probably look something like this:

 else if (minutes <= 0.0f && seconds <= 0.0f) {
         timerText.text = "Game Over";
         Debug.Log ("go");
     }

OR

 else if (Mathf.Approximately(minutes, 0.0f) && Mathf.Approximately(seconds, 0.0f) {
         timerText.text = "Game Over";
         Debug.Log ("go");
     }

Hope that helps!

~LegendBacon

Never compare floats directly, but instead use Mathf.Approximately:

Also, in this particular case, when seconds = 0 the first branch might execute again if (seconds == 0), so we should doing something about that, just in case. Also, since you are using seconds -= Time.deltaTime, typically seconds are reduced below 0, and this is the main cause of the problem. So, here’s an Update() that works (I tested it):

    void Update()
    {
        if (minutes > 0 && Mathf.Approximately(seconds, 0))
        {
            minutes--;
            seconds = 59;
            timerText.text = minutes.ToString() + ":" + seconds.ToString("f0");
            Debug.Log(minutes + " " + seconds);
        }
        else if (seconds > 0)
        {
            seconds -= Time.deltaTime;
            timerText.text = minutes.ToString() + ":" + seconds.ToString("f0");
            Debug.Log(minutes + " " + seconds);
        }
        else if (Mathf.Approximately(minutes, 0) && seconds <= 0)
        {
            timerText.text = "Game Over";
            Debug.Log("go");
        }
    }