- Home /
How do I add a Game Over text to my timer?
I'm trying to add a game over text after my timer runs out (hits 0) but I can't seem to figure it out. Here is my code for the timer:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Timer : MonoBehaviour {
public float myTimer=99;
public Text TimerText;
private bool timerIsActive=true;
public Text GameOverText;
// Use this for initialization
void Start () {
TimerText = GetComponent<Text> ();
}
// Update is called once per frame
void Update () {
if(timerIsActive){
myTimer -= Time.deltaTime;
TimerText.text = myTimer.ToString ("f1");
print (myTimer);
if (myTimer<=0){
myTimer = 0;
timerIsActive = false;
print ("Game Over");
}
}
}
}
your script is fine. i think your script is not attached with the text component and when you try to GetComponent (); it throws exception and never print Game Over.$$anonymous$$ake sure your script is attached with the text component and if your script is not attached with the text component then simply remove the below line from script and pass manually.
TimerText = GetComponent ();
Answer by Laurence_B · May 02, 2017 at 06:57 PM
You can set a Canvas Active. I think you have to import the Canvas into the script as a Game Object because the SetActive command only works for those. Dont forget to set the GameOverCanvas in your Unity project as unactive before running
public GameObject GameOverCanvas; //pull the game over canvas / game object in the slot in the inspector
...
...
...
if (myTimer<=0){
myTimer = 0;
timerIsActive = false;
GameOverCanvas.SetActive(true)