- Home /
The question is answered, right answer was accepted
Coroutine while(bool) kills Unity
Why does it put Unity into a endless loop? I am relocating some code from Update into Coroutines, because I think it is just cleaner and resource wise better that way (using if in Update isn't needed most of the time and can be avoided using events and coroutines imo). It puts Unity instantly as the Coroutine is started into an endless-loop state
Code is pretty simple
while (flag) DoSomething()
yield return null;
and somewhere i would set the flag to false
Answer by fffMalzbier · Oct 08, 2019 at 02:03 PM
Im not sure if its just bad formatting but like it formatted yield return null; will only be called after flag is false.
Try this:
while (flag) { DoSomething() yield return null; }
yield return null should only be called after the flag is false, else the while loop would be called only once. I leave out braces when I only have one statement following, keeps it short
That's not really how coroutines work, have you tried that block as posted? What is your desired behavior here?
The yield return null
here basically just means "give control back to Unity and come back here on the next frame". Without that, you'll get a blocking operation as you've already noticed.
Wait, so yield return null doesn't ter$$anonymous$$ate the coroutine?
Follow this Question
Related Questions
start coroutine everytime 2 Answers
UI Text not changing color [C#] 2 Answers
Coroutine loop not working 1 Answer