Friday, October 9, 2015

Unity 3D: Compiled game freezes or crashes on exit

Sometimes -- and it seems to happen much more often when dealing with blocking resources (such as serial ports) or multiple threads -- your built Unity game will crash or hang when calling Application.Quit ().

First and foremost, check your logs and make sure you're not throwing an exception as the program exits. And of course check your code to make sure you haven't inadvertently made an infinite loop somewhere. Clean up any resources that may not be handled automatically -- for instance, close serial ports, kill threads, etc.

Assuming you've done all that and you're still freezing when the program exits, try replacing Application.Quit () with the following lines of code:

if (!Application.isEditor)
{
     System.Diagnostics.Process.GetCurrentProcess().Kill();
}

There seems to be the occasional bug that rears its head with Application.Quit (), so we're using a .NET command to kill the process directly. We are also checking to make sure that we're not in the Editor, because if you run this line of code from the Editor, it will close.

No comments:

Post a Comment