- Home /
How can I display the GAME OVER word across the centre of the screen when the when my timer hits zero?
Hello So I want to create a GAME OVER word that will be displayed on my screen when the timer hits 0. I tried to create a text component as well as declaring it in my script below but doesn't seems to work. I also untick the text component so that it doesn't appear when I start the game, but when the Timer hits 0, nothing appear. So please send help if you can and thank you for your time. Here's my Timer script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public float timeLeft = 20;
public bool timeIsRunning = false;
public Text timeText;
public Text gameOverText;
public Color myColor;
// Start is called before the first frame update
private void Start()
{
//Automatically starts the timer
timeIsRunning = true;
}
// Update is called once per frame
void Update()
{
if (timeIsRunning)
{
if (timeLeft > 0)
{
timeLeft -= Time.deltaTime;
}
else
{
Debug.Log("Out of time!");
timeLeft = 0;
timeIsRunning = false;
}
DisplayTime(timeLeft);
}
void DisplayTime(float timeToDisplay)
{
if (timeToDisplay < 0)
{
timeToDisplay = 0;
}
else if (timeToDisplay <= 6)
{
timeText.color = myColor;
}
else if (timeToDisplay == 0)
{
gameOverText.text = "Game Over";
}
float minutes = Mathf.FloorToInt(timeToDisplay / 60);
float seconds = Mathf.FloorToInt(timeToDisplay % 60);
timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
}
}
Answer by CodesCove · Dec 05, 2021 at 07:28 PM
DisplayTime never gets to the (timeToDisplay==0)
. After the (timeToDisplay <= 6)
it just skips the next if-statement because it will return true and you are using else-statement after it.
So it shoud be (without else)
if (timeToDisplay == 0)
{
gameOverText.text = "Game Over";
}
I also think that the other else statement is pretty useless in this context. Maybe check the whole logic to optimize the code..
Also make sure your Timer is in the active Game Object. Otherwise it will not run since the Update() is called only the for active GO's and enabled Components.
Answer by bsoul41 · Dec 05, 2021 at 09:07 AM
if you unticked the text you need to ticked back when time is over use textui.SetActive(false) when game starts and set it setactive(true) when time is over .
Answer by EvilBob99 · Dec 06, 2021 at 08:59 AM
@CodesCove is right an you can also disable and enable the renderer when ever you want with this bit of code
whatevername.GetComponent().enabled = false/true;
I hope this also helps you can use ui with this too but im not sure the actual code but your a better programmer im sure you can work it out
Your answer
Follow this Question
Related Questions
Making a Timer Out out of 3D Text using C#. 1 Answer
Timer going negative...Help 2 Answers
Distribute terrain in zones 3 Answers
Countdown timer into text c# 1 Answer
Problems in c# countdown timer 1 Answer