- Home /
problem with coroutines
I'm not all that familiar with coroutines in Unity. I have this:
private IEnumerator TurnCoroutine()
{
Debug.Log("TurnCoroutine() 1");
yield return DoTurn();
Debug.Log("TurnCoroutine() 2");
}
private IEnumerator DoTurn()
{
//TODO: do stuff
Debug.Log("DoTurn() 1");
yield return new WaitForSeconds(2); //temp
Debug.Log("DoTurn() 2");
}
And I would expect it to log like this:
TurnCoroutine() 1
DoTurn() 1
TurnCoroutine() 2
DoTurn() 2
But it only logs this:
TurnCoroutine() 1
TurnCoroutine() 2
it doesn't seem to run DoTurn(), can anyone explain to me why?
Answer by Bunny83 · Nov 10, 2014 at 08:14 PM
Because coroutines have to be started with StartCoroutine ;)
private IEnumerator TurnCoroutine()
{
Debug.Log("TurnCoroutine() 1");
yield return StarCoroutine(DoTurn());
Debug.Log("TurnCoroutine() 2");
}
ah thanks, just found out myself, was already typing my answer before yours appeared
Answer by Steven-1 · Nov 10, 2014 at 08:16 PM
Why is it that I always can't seem to find the answer until I ask the question, sigh, just found out I have to this:
yield return StartCoroutine(DoTurn());
instead of
yield return DoTurn();
which I guess is logic, but if that is desired, why does what I did compile?
It compiles because your method DoTurn just returns an object and that you returned to the coroutine scheduler of your TurnCoroutine. The scheduler will treat all values that aren't derived from YieldInstruction like "null" and will wait 1 frame.
The object your DoTurn method returns is an instance of a compiler generated (internal) class that implements the IEnumerator interface which actually contains the code of your coroutine. When you pass such an object to StartCoroutine you don't actually "start" or "run" the code inside your coroutine. You just pass this object to Unity and the scheduler will store it internally and "schedule" the next "iteration" of your generator method depending on what you returned in your coroutine.
Translation: Coroutines are a Unity hack, not a language feature. As such there are cases where the compiler won't detect problems, because your code is still legal in the language.
Your answer
Follow this Question
Related Questions
NullReferenceException in StartCoroutine 1 Answer
Flash image while ammo is low - coroutines? 3 Answers
Coroutines not passing yield 1 Answer
Collection Change During Iteration 0 Answers
Why doesnt my coroutine ever end? 2 Answers