Problem with coroutines (121906)

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?

2 Answers

2

Because coroutines have to be started with StartCoroutine :wink:

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

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?

thanks for the info

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.