- Home /
Coroutine counts down to zero, but doesnt show "countdown has reached 0" on the exact moment the timer hits 0
Greetings, everyone reading this post!
I'm practicing making a coroutine countdown timer, and im pretty proud of my progress, but one thing baffles me: no matter where i put the "if (CountdownSeconds == 0)", it always posts the "Countdown has reached 0!" before the Debug.Log shows 0 on the countdown. and if I put it outside underneath the curly brackets, it takes a second until it shows "Countdown has reached 0!"
My goal is to get it to show "0", then "Countdown Timer has reached 0!" immediately, but after the countdown hits zero. Please show me the way, and explain how I could fix it!
just copy and paste my code! p.s. use the spacebar to StartCoroutine(); using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CoroutineTest : MonoBehaviour
{
[SerializeField] float CountdownSeconds = 3f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(CountdownTime());
}
else
{
StopCoroutine(CountdownTime());
}
}
IEnumerator CountdownTime()
{
while(CountdownSeconds >= 0)
{
Debug.Log(CountdownSeconds);
CountdownSeconds--;
yield return new WaitForSeconds(1);
if (CountdownSeconds <= 0)
{
Debug.Log("Countdown has reached 0!");
}
}
StopCoroutine(CountdownTime());
Debug.Log("Coroutine Ended Successfully!");
}
}
Answer by Bunny83 · Sep 07, 2019 at 12:17 AM
There are several issues here. First of all this line makes no sense at all and does nothing except producing garbage:
StopCoroutine(CountdownTime());
Each time you call "CountdownTime()" you create a new statemachine object. Passing it to StopCoroutine does nothing since this specific statemachine hasn't yet been registrated as coroutine.
About your issue when you see which debug log statement: You first print the value of your variable and then you reduce it by 1. Just switch the order of those two lines. So instead of:
Debug.Log(CountdownSeconds);
CountdownSeconds--;
just do:
CountdownSeconds--;
Debug.Log(CountdownSeconds);
Another thing you might want to change is to switch your variable type from float to int because you seem to only change your variable in whole units. Using a float could possible create additional issues like getting values like 0.99999999 instead of 1.
Thanks for your assistance and feedback! I tried switching them as you instructed, but it ended up counting from 2 down to -1. I fixed the -1 by making my while as CountdownSeconds > 0, but I dont know why it doesnt count from my assigned CountDownSeconds.
Your answer

Follow this Question
Related Questions
Create a countdown in C# (inside Coroutine) 2 Answers
Making a fill take exactly n seconds to complete 2 Answers
Countdown Timer 1 Answer
countdown/countup timer 1 Answer
How to stop a Countdown Timer? 1 Answer