Itai Elidan
Itai Elidan

Reputation: 272

IEnumerator stops after yield return new WaitForSeconds() unity

I have a function that calls an IEnumerator but every time I try to run it the IEnumerator stops right after yield return new. It logs "start" in the debug but doesn't log "over".

public void StartAnimation()
{
   StartCoroutine(ResizeText());        
}

IEnumerator ResizeText()
{        
    Debug.Log("start");
    yield return new WaitForSeconds(0.1f);
    Debug.Log("over");
}

Upvotes: 0

Views: 5235

Answers (1)

Brandon
Brandon

Reputation: 23500

Actually this code is perfectly valid (and it makes sense considering how Coroutines are implemented and how they work). It also makes sense because it's a yield return and not a yield break.. so technically the code should be working as is.

I also tried it in a blank Scene..

First, you are "probably" killing your scene before the time passes.

Reproduce:

Create a blank scene.. Add a script to the camera. Add:

void Start()
{
    StartCoroutine(meh()); //OR: StartCoroutine("meh"); //Both will work just fine..
}

private IEnumerator meh()
{
    Debug.Log("Hello");
    yield return new WaitForSeconds(2.0f);
    Debug.Log("Bye");

}

When you run it, it will print "Hello", then it waits 2.0 seconds and it prints "Bye"..

Therefore, something else is missing/wrong in your scenario..

The only time the code will NOT run after a yield statement is when you do (yield break):

private IEnumerator meh()
{
    Debug.Log("Hello");
    yield return new WaitForSeconds(2.0f);

    Debug.Log("Bye");
    yield break;

    //NOTHING here will be executed because `yield break;` is like a permanent exit of the Coroutine..

    //Therefore these statements below will NOT execute..
    Debug.Log("Reboot");
}

Upvotes: 3

Related Questions