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!");
}
}