- Home /
Only the first half of my coroutine works
It could be a very simple mistake I'm new to Unity. Here's the script:
private void OnCollisionEnter2D(Collision2D collision)
{
// SPIKE
if (collision.gameObject.tag == "Spike")
{
StartCoroutine(DeathTimer());
StopCoroutine(DeathTimer());
}
}
// DEATH ON SPIKE
IEnumerator DeathTimer()
{
Debug.Log("Started");
Destroy(player);
yield return new WaitForSecondsRealtime(3);
SceneManager.LoadScene(0);
Debug.Log("Ended");
}
I can see "Started" printed in the console, but no "Ended". And the player object is destroyed, but the scene isn't loaded. Any clues on how to fix this?
Answer by FeedMyKids1 · Jan 28, 2021 at 07:30 AM
If you're destroying the object containing the coroutine, it will stop running (Destroy(player) will stop the coroutine if the player is where the coroutine is running). Coroutines are objects that get instantiated on a Monobehaviour when you call StartCoroutine and that object is managed by the calling object - Say, for example, your player object is a monobehaviour calling the coroutine, it then has a reference to the coroutine object and when OnDestroy is called on the player, it stops all coroutines on it.
Don't call StopCoroutine. This is another problem I can see here. It will immediately stop the coroutine. Once you call StartCoroutine, it will run its course then be 'picked up' by the garbage collector once it's finished.
A reason to use StopCoroutine might be that your player is dead but navigates in a coroutine - in that case you call stopcoroutine so you don't have a weird zombie player running around.
Coroutines outlive the function that is calling them. Which means, StopCoroutine is called, regardless of whether the coroutine has finished or not. You don't need to call StopCoroutine. It will finish automatically, and stop running anyways.
Your answer
Follow this Question
Related Questions
Waiting between pingpong loops 2 Answers
C# yield waitforseconds 3 Answers
c# - Having problems with the WaitForSeconds() method. 1 Answer
Yield WaitForSec help in C sharp 1 Answer