Unity 3d freezes when MouseButtonDown is used

Hi,

I know it’s something to do with an infinite while loop and that it needs to be resolved. However, I don’t know where to resolve it.

Here’s the code:

public class RotateRight : MonoBehaviour
{
    //void start can't be used for these buttons.
    public GameObject ship;
    public GameObject button;
    bool isPressed = false;
    //The object that's moving is the ship, not the player.
    public float Force = -5f;

    void OnMouseDown()
    {
        isPressed = true;
        Debug.Log("Hello");
    }

    void Update()
    {
        while (isPressed == true)
        {
            if (Input.GetMouseButton(0))
            {
                ship.transform.Rotate(0, 0.5f, 0);
                //when this button is pressed, the ship will move 1 degree to the right (y axis)
            }
            else
            {
                isPressed = false;
            }
        }
    }

}

Whenever this runs and I click the button it’s attached to Unity just doesn’t respond and I end up having to close it down.

Your while loop will never break, because it’s waiting for GetMouseButton to return false - and it never will, because the GetMouseButton return value is the same during the entire frame - and the frame won’t end until Update method returns, which won’t happen until the loop is running.

The Update method is being called from Unity’s internal loop. By looking at your code, I think that all you need to do is to change while to if

Thanks! I got so confused on this