I want to have background threads in edit mode that exit cleanly when the play mode is started.
I use a custom object that spawns some threads. However, when I enter the play mode by clicking the play button the threads are instantly killed.
My idea was to stop the threads gracefully in OnDestroy() method of the MonoBehaviour but at the time it gets executed the threads have already been forcefully killed.
Concretely, here’s the basic structure:
public class ThreadStuff {
ThreadStuff() {
// spawn some System.Threading.Threads here
}
public void ShutDown() {
// signal the threads to shut down here
}
}
[ExecuteInEditMode]
public class MyScript : MonoBehaviour
{
private ThreadStuff stuff;
void Start() {
stuff = new ThreadStuff();
}
void OnDestroy() {
// by the time we get here stuff is already set to null
// and the threads have been killed
// this will crash
stuff.ShutDown();
}
}
So, two questions:
- Why is the member variable “stuff” already set to null when OnDestroy() gets called?
- Is there way to cleanly exit the threads when moving from edit to play mode?