Everything works fine when clicking Play the first time. After stopping once, pressing the play button again (or closing the editor) results in Unity freezing; I must close Unity via TaskManager. When reloaded it then works again, once, at which point I must repeat the process.
I assume this is being caused by threads/sockets remaining active after stopping the program in the Unity editor. Is there a way to determine which thread(s) / what is causing the problem?
There are probably multiple reasons for this to happen, but I have encountered two so far:
Failure to shut down background threads.
A destructor (finalizer) that hangs (deadlocked).
Connecting Visual Studio to Unity.exe through “Debug->Attach to process…” (not “Attach to Unity”), pausing it and looking at Parallel Stacks (Debug->Windows->Parallel Stacks) can give you some insights into whats going on.
Edit: Since this writing I’ve also seen a recursive function lock up Unity. 16 levelx max breadth-first search type of function. No error, Just plain old hang. Changing the function to use a queue instead of recursion fixed it.
If you write any Destructors, they get called on the NEXT time you press play. Just before your new instances are constructed. It can confuse your debugging no end. I’ve had a few issues with every 2nd play crashing, and it’s always been to do with cleaning up / closing objects correctly.
This was seen on 2017.2
Using a callback to forward debug output from a plugin into the Unity log can in some cases cause a hang on second run. See this forum post for more details.