Do while makes unity crash.

Hello, I was writing some simple code then I went through something strange…
My unity editor crashes just if I enter play mode with the 2 incriminated lines in void Update(), that I’ve signed as a comment, are active. Why should a simple do while making unity crash?
I’ve even tried other forms like while (!Ewall) but nothing changes.
Any kind of help would be appreciated, thank you.

bool Ewall=false;

    void Start(){
    }

    void Update ()
    {
       
            var dir = Vector3.zero;

            if (Input.GetKey (KeyCode.UpArrow))
                dir = Vector3.forward;
   
            if (Input.GetKey (KeyCode.DownArrow))
                dir = Vector3.back;

            if (Input.GetKey (KeyCode.LeftArrow))
                dir = Vector3.left;
        //do {
            if (Input.GetKey (KeyCode.RightArrow))
                dir = Vector3.right;
        //} while(Ewall==false);
            if (dir != Vector3.zero && !isTumbling) {
                StartCoroutine (Tumble (dir));
            }   
    }

void OnTriggerEnter(Collider other){
        if (other.gameObject.CompareTag ("Ewall")) {
            Ewall = true;
            Debug.Log ("EastWall!");
        }
    }
}

A while loop will tie up the process indefinitely until the condition no longer resolves to true. Since you aren’t changing the condition inside the while loop, it can never exit the loop.

Update() is called one per frame, so you don’t need a while loop.

2 Likes

Thank you, problem solved, but I still can’t understand why unity crashes instead of reporting an error or something… It has to be fixed.

It’s your fault for writing code that causes the program to be literally be stuck in an infinite loop. This is a standard thing that you’re expected to avoid doing as a programmer. Unity can’t make you not make bad decisions.

1 Like

FYI, in some cases you can avoid the crash. When you notice that Unity appears to have locked up, and you suspect it’s your code, you can attach the debugger and put a breakpoint within your loop. In some cases you can modify the values in the debugger, causing the loop to end. It’s not always feasible, but I’ve prevented crashes this way before.

1 Like