- Home /
while loop issue
I can't figure out why I am freezing unity with my while loop. I am trying to check the sate of a boolean variable in another script called "IsObjectThere". If that Boolean variable is not true and if the mouse button is up then I it to remain in the while loop until the canSpawn variable is true. Once its true I want to break the while loop.
If I run my code without the while loop it runs fine. As soon as I enter the while loop it freezes unity. Below is the part of my code I am dealing with.
var objs : GameObject[];
var respawn : GameObject;
var IsObjectThere : isObjectThere;
var waiting : boolean;
private var obj : GameObject;
function Start()
{
if (respawn==null)
respawn = GameObject.FindWithTag ("Respawn");
}
function Update()
{
if (Input.GetKeyDown (KeyCode.Mouse0))
{
obj = Instantiate(objs[(Random.Range(0, objs.Length))], respawn.transform.position, respawn.transform.rotation);
obj.transform.parent = Camera.main.transform;
IsObjectThere = obj.GetComponent(isObjectThere);
}
if (Input.GetKeyUp (KeyCode.Mouse0)&& IsObjectThere.canSpawn)
{
DropObject();
}
if(Input.GetKeyUp (KeyCode.Mouse0) && (!IsObjectThere.canSpawn))
{
waiting = true;
while(waiting)
{
if (IsObjectThere.canSpawn)
{
waiting = false;
}
}
}
}
function DropObject ()
{
obj.transform.parent = null;
obj.GetComponent(Rotate).enabled = false;
obj.gameObject.tag = "placedObject";
Debug.Log (IsObjectThere.canSpawn);
}
Answer by Shiroi24 · Mar 05, 2013 at 06:37 AM
Unity "Freezes" because it is stuck in a while loop during update(). And since update() never finishes, Unity never gets to the next step until waiting is false. But since Unity can't update again(because it is already stuck in an update), IsObjectThere.canSpawn will never be updated and causes Unity to get stuck.
Whats the best way to handle a situation like that? If you could give me an example of how I might proceed that would be greatly appreciated.
I would separate out waiting and not waiting with if statements.
if(waiting)
{
codeForWhileWaiting;
}
else
{
codeForWhenNotWaiting;
}
Either that or I would use a finite state machine.
Your answer
![](https://koobas.hobune.stream/wayback/20220613093836im_/https://answers.unity.com/themes/thub/images/avi.jpg)