c# – Using do while loop freezes unity

c# – Using do while loop freezes unity

Your do while loop will execute Rigidbody2d.velocity = new Vector2(1f, 0f); every single time around. Theres nothing in that loop thats changing. If you did:

while (x < y)
{
    a = 5;
    x++;
}

There wouldnt be any point in doing that. Simply a = 5 would have the same effect, just a lot less uneeded looping.

On top of that, youre not changing the value of x at all. Thats whats causing the issue. Youre basically doing

while (x < y)
    a = 5;

If x was less than y at the start, x will always be less than y, so it will keep executing the body of the while loop forever, and thus Unity is stuck in the Update method.

This has nothing to do with the fact that Update is called once per frame. This is just a simple infinite loop caused by using a condition that isnt changing. This would block the program even if it was in a different function.

Heres something you can do instead:

// Using a property will always return the targets X value when called without having to 
// set it to a variable
private float X 
{ 
    // Called when getting value of X
    get { return Rigidbody2d.transform.position.X; } }  

    // Called when setting the value of X
    set { transform.position = new Vector2(value, transform.position.y); }  
}
private bool isMoving = false;

private void Update () 
{  

    if (X < -4 && !isMoving)
    { 
        Rigidbody2d.velocity = new Vector2(1f, 0f); // Move plank till it reaches point B
        isMoving = true;
    }
    else if (isMoving) 
    { 
        Rigidbody2d.velocity = new Vector(0f, 0f);  // You probably want to reset the 
                                                    // velocity back to 0
        isMoving = false;
    }                                               
} 

As the comment above your Update-method suggests, Update() is called once per frame.
A while-loop will block the Update() until the condition is fullfilled, but it will never be fulfilled when you are blocking the Update()-method.

Try something like this

void Update() 
{
     if(this.transform.position.x < -4) 
          Rigidbody2d.velocity = new Vector2(1f, 0f);
}

Imagine the gameloop in unity looks something like this (very over-simplified)

while(running) 
{
   // Start of frame
   CallUpdateOnGameObjects();
   ProcessPhysics(); // this is where the rigidbody is moved
   DrawEverything();
   // End of frame
}

So when your update method is called, you are starting your while-loop, but the condition for the while loop can never be fullfilled, because the gameloop wont ever be able to reach ProcessPhysics().

For reference see
https://docs.unity3d.com/Manual/ExecutionOrder.html

c# – Using do while loop freezes unity

Leave a Reply

Your email address will not be published.