Coroutine not looping

Could somebody explain why size increments to 1 and stops??

private IEnumerator MyCoroutine()
    {
        while(size < 10)
        {
            size++;
            yield return null;
        }

        yield return new WaitForEndOfFrame();
        Debug.Log("full size");
    }

Have you tried using if, instead of while?

Also have you used startcoroutine(MyCouroutine()); earlier in the script?

There might also be a need to use a variable to determine the speed at which Size increases, every time I use ++, the value increases super fast.

As suggested, make sure you are calling your coroutine correctly. Also note, yield return null waits one frame, which means your while loop will go super fast overall.

@JoshWindsor The while statement makes more sense here if OP wants a loop to increase size based on the yield time and loop. An if statement would only increment it once when the coroutine is called.

That makes sense :slight_smile: I haven’t been using while loops so that’s why I suggested an if statement. I think I will do some research and start using them myself. Tyvm!

@JoshWindsor The while statement makes more sense here if OP wants a loop to increase size based on the yield time and loop. An if statement would only increment it once when the coroutine is called.[/QUOTE]

Hey, yeah I’m using start coroutine so should all be good there. Not concerned about the speed of the loop. This was just a snippet to simplyfy and demonstrate my problem

Your snippet works as expected for me, “full size” is logged when size is 10.

  • Maybe the game object your coroutine is running on is destroyed and therefore the coroutine stopped?
  • Maybe something else is changing size while the coroutine is running?
  • Or your actual code is subtly different to the snipped you posted?
3 Likes

Maybe you’re using StartCoroutine() in Start() instead of Update()

Why would you use it in Update? That’s bad advice considering the posted code. Not only would that start up the coroutine every frame, thus quickly increasing the value of size due to multiple coroutines incrementing it, it also would continue to run the coroutine beyond it’s use.

3 Likes

Solved it, thanks for the suggestions, tried running the code in a isolate script on a new gameObject and ran fine.

Another script was disable and re-enabling the object, interrupting the coroutine

Interesting, I didn’t know a coroutine’s execution could be stopped by disabling it’s associated GameObject.

1 Like

I don’t know if was the object being disabled, but it was the child of a child of a child etc that had the script attached, and something was happening on the way