- Home /
While Loop & Bool (infinite loop freeze)
This is probably a really simple question, can't figure it out because I'm very new so any help would be appreciated
I want to run a while loop, and while my game object is spawned you can click it. But I'm not sure how to execute a while loop where the condition is a Boolean.
As soon as the chest is spawned and the chestSpawned == true, I get frozen in unity as its infinite. In 5 seconds the chestSpawned will return false but unity gets frozen before then so I'm not sure how to fix this.
Here is what I have.
while (chestSpawned == true)
{
Debug.Log ("Click the chest!!!");
}
Why do you need the while loop? Can you just put something into an Update() function like
if (chestSpawned == true)
{
Debug.Log("Click the chest!");
}
?
Answer by Justinger · Jan 08, 2018 at 09:07 PM
If you have it in something like an update function, you don't need to use a "while" loop. The game automatically runs it once a frame. So try doing if(chestSpawned) Debug.Log ("Click the chest!!!");
A more difficult but maybe cleaner approach would be to trigger a coroutine that prints every frame until 5 seconds is up, and then kills itself. I doubt that would be needed in this case though.
I always appreciate a simple answer, thanks a lot I totally overthought it!
Your answer
![](https://koobas.hobune.stream/wayback/20220612150110im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Display a loading while processing a while loop 1 Answer
Do-While loop 2 Answers
While loop freezes unity 3 Answers
Quaternion.Slerp issue 1 Answer