-1
\$\begingroup\$

I'm trying to make a countdown timer in Unity, and I've been able to make the timer count down from 10. However, I can't stop it at 0. I've tried putting it in a while loop but it didn't help, it actually made the timer start at 0.

float counter = 10.0f; public TextMesh countdown; void Start () { countdown = gameObject.GetComponent<TextMesh>(); } void Update () { counter -= Time.deltaTime; countdown.text = "Time Left:" + Mathf.Round(timeLeft); if (counter <= 0) { Debug.Log("Hello"); } } 
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Because the update is called constantly, you're always running through this;

counter -= Time.deltaTime; countdown.text = "Time Left:" + Mathf.Round(timeLeft); 

and never really stopping.

In order to stop, you could try something like a flag- something to tell your loop when to stop the countdown. Though because of the simplicity of your program, you could try this, which doesn't use a flag but rather outputs the time left based on your current condition:

float counter = 10.0f; public TextMesh countdown; void Start () { countdown = gameObject.GetComponent<TextMesh>(); } void Update () { if(counter > 0) { counter -= Time.deltaTime; countdown.text = "Time Left:" + Mathf.Round(timeLeft); } else { Debug.Log("The counter has stopped."); } } 
\$\endgroup\$
1
\$\begingroup\$

Try with

void Update () { if (counter > 0) { counter -= Time.deltaTime; countdown.text = "Time Left:" + Mathf.Round(timeLeft); } else { Debug.Log("Hello"); } 

Note that this will print "Hello" in the console many time per seconds as soon as the counter reaches 0. This is what your code was doing, I don't know if it was on purpose.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.