- Home /
Unity Freeze when im using while timer
Hello. When i try run this script it freezes unity.
I read about this problem it is problem when while loop is infinite but in my case it isnt.
I use this code in update function.
Thanks for answers :)
Code Here:
for (int i = 0; i < max; i++){
while (wait > 0)
{
Debug.Log("-");
wait -= Time.deltaTime;//decressing timer
}
food.GetComponent<SpriteRenderer>().color = Color.gray; //set color
food.transform.position = Random.insideUnitCircle + new Vector2(transform.position.x, transform.position.y); //set positions
Instantiate(food); //create gameobject
count++;
wait = 100; //setting it back up
}
It's not an infinite loop, true, but running your own loops in Update (which is itself a loop) gets tricky if those loops take longer to process than the duration of a single frame. It means that control won't be returned to Unity to start rendering the next frame. It's what's known as a blocking call - Unity is blocked from continuing. The Debug.Log() you have in the loop is an example of an expensive call. It writes the entire stack trace for each log entry. You can turn that off in your console settings. To alleviate the problem, you can accomplish computationally intensive work in a Coroutine, as GamitusLabs suggested. Take time to learn them, as they're very useful in many situations.
Answer by GamitusLabs · Oct 23, 2018 at 05:45 PM
It sounds to me like you want this to be in a Coroutine...
https://docs.unity3d.com/Manual/Coroutines.html
https://docs.unity3d.com/ScriptReference/Coroutine.html
https://unity3d.com/learn/tutorials/topics/scripting/coroutines
Your answer
![](https://koobas.hobune.stream/wayback/20220612180832im_/https://answers.unity.com/themes/thub/images/avi.jpg)