Editor thread lifetime

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?

Hi, have you tried EditorApplication.playmodeStateChanged ? Maybe this event fires before threads gets killed.

Also, as a workaround, maybe you can use your own “Start play mode” button and avoid using Unity’s one, so you can close your threads before asking Unity to enter playmode (but there may still be a problem when recompiling though). Using EditorApplication.ExecuteMenuItem(“Edit/Play”) should work.

EDIT: have you tried OnDisable callback, maybe it’s called before OnDestroy & before the threads are killed