Unity is mysteriously freezing / locking up
Ever wonder why sometimes Unity may freeze (or lock up) forever, requiring you to end the process with Task Manager? Here is one reason which has bitten me many times over the years. I admit that even though I know better, I keep repeating the same mistake. Maybe it will help someone out (or future me).
Do a global search in all of your scripts for any while loops such as:
while (Application.isPlaying) {
DoSomething();
if (someVariable) break;
}
You may think, oh that break will always end the loop… but will it really? Depends on the code inside the while loop, obviously.
In any case, I now try to always put a timer inside that will abort the loop after a sane amount of time:
float timer = 0f;
while (Application.isPlaying && timer < 3f) {
yield return null;
timer += Time.deltaTime;
}
3 seconds is just an example, it really depends on what’s going on inside the loop and how long you should reasonably expect the loop to execute before it should stop.
Alternately, I often do this so I can see in Unity Console that something is probably broken:
float timer = 0f;
while (Application.isPlaying) {
yield return null;
timer += Time.deltaTime;
if (timer > 3f) Debug.LogWarning("Timed out waiting for loop to finish!");
}