Why Does This Script Freeze My Entire Unity Editor?

For some ungodly reason, whenever I try to implement this script, when I press play to test the game, it doesn’t actually play. The cursor disappears and it hangs on the editor, not allowing me to do anything at all, which then requires me to close the program.

I can NOT find the reason why this simple script would do this.

I am also very new to scripting, so there could be something I am missing entirely.

function Start () {
	Screen.lockCursor = true;

}

function Update () {
	while (Screen.lockCursor == true) {
		if (Input.GetKeyDown(KeyCode.Escape)) {
		unlockCursor();
		}
	}
	
	while (Screen.lockCursor == false) {
		if (Input.GetKeyDown(KeyCode.Escape)) {
		lockCursor();
		}
	}
}

function lockCursor() {
		Screen.lockCursor = true;
}

function unlockCursor() {
		Screen.lockCursor = false;
}

If anyone could explain why this is happening, I would greatly appreciate it.

while (true) { } // Infinite loop
You got an infinite loop. The Update function won’t return until the Screen.lockCursor is false etc. This means it stalls the game since Unity can’t update anything else until your script finishes its update call.

Try something like this instead:

function Update () {
    if (Input.GetKeyDown (KeyCode.Escape))
        ToggleCursorLock ();
}

function ToggleCursorLock () {
    Screen.lockCursor = !Screen.lockCursor;
}

Or if you don’t like having small functions that give instructions names:

function Update () {
    if (Input.GetKeyDown (KeyCode.Escape))
        Screen.lockCursor = !Screen.lockCursor;
}

Hope it helps.

While loops freeze the unity editor? The console should throw an error. Thats totally not how I thought the engine would behave if you use a while loop.