Unity Sandalone player hangs on exit, and editor hangs on leaving play mode

I have a problem that cropped up recently in my project, where attempting to close the window, via clicking the x in the title bar, or by leaving play mode in the editor, will result in a program freeze, and an eventual “This program has stopped responding” dialog.

I’ve narrowed the problem down to my mesh generation function, found here:

https://github.com/JapaMala/armok-vision/blob/master/Assets/MapGen/Meshing/VoxelGrid/VoxelGenerator.cs

which uses a 2D triangulation library here:

https://github.com/JapaMala/armok-vision/blob/master/Assets/MapGen/Meshing/Poly2Tri/P2T.cs

But I have no idea what could be causing the behavior, other than the fact that it only happens when the mesh generation is happening in a separate thread. When I set the mesh generation to happen in the main Unity thread, the issue can’t be reproduced, but the mesh generation is also really slow.

The project can be built and run from the github repo, but requires also running Dwarf Fortress with a plugin installed to function.

Sounds like a race condition. Multi-threading can be tricky, and if two threads try to set a field or property at once, they’ll deadlock, and both freeze. There’s no easy way I’m aware of to track down your race condition; the best thing to do is write a program so race conditions are protected against and handled from the start. Since you probably haven’t done that, you can either rewrite your scripts from the base up with multi-threading in mind, or use logging to try and track it down.

Honestly, that 1000+ line script is so messy that I would rewrite and restructure from the base up. With code like this, you’re bound to see more bugs than you can shake a stick at, and if you ever have to go back and work on it, you’ll spend hours just trying to unravel the spaghetti.

Yeah, I’m not proud of the spaghetti, and but I’m not sure if there’s a clean way to handle all the hundreds of possibilities of corner types I’m dealing with there.

I’ll try and see what stuff is being read between threads and try to see what’s up.

There’s always a clean way to handle almost every situation in C#. At the very least, code specific to each type of corner could be moved into separate classes. You’re working in an object oriented environment, and you’re going to find that breaking things down into their component classes will help you keep things structured and orderly.

Also, you’re very liberal with switches…any time I see that amount of switches, odds are the logic they’re trying to represent can be turned into a relatively small algorithm. I’d consider other approaches to doing what your commonly used switches can be used for.