Jump to content
Unity Insider Forum

Coroutine while(bool) kills Unity


Nyen Dev

Recommended Posts

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 

Link zu diesem Kommentar
Auf anderen Seiten teilen

Doing something conditionally only once is done with an if statement. A while statement always means a loop. The braces only define what is being executed conditionally or multiple times. Omitting the braces means just including the next statement in the if or while statement, so your original code is equivalent to

while (flag)
{
  DoSomething() 
}

yield return null; 

Which means you're infinitely executing DoSomething(), since the waiting part (yield return null) is never reached.

Link zu diesem Kommentar
Auf anderen Seiten teilen

Just now, Sascha said:

Doing something conditionally only once is done with an if statement. A while statement always means a loop. The braces only define what is being executed conditionally or multiple times. Omitting the braces means just including the next statement in the if or while statement, so your original code is equivalent to


while (flag)
{
  DoSomething() 
}

yield return null; 

Which means you're infinitely executing DoSomething(), since the waiting part (yield return null) is never reached.

I know it is the same, just keeps it short. And I do want it to repeat. The flag is changed somewhere else in the code when other conditions are met, and they are for sure. But starting this coroutine instantly kills unity 

Link zu diesem Kommentar
Auf anderen Seiten teilen

Archiviert

Dieses Thema ist jetzt archiviert und für weitere Antworten gesperrt.

×
×
  • Neu erstellen...