EditorApplication.playmodeStateChanged does not work

I have a menu command that when executed calls

EditorApplication.playmodeStateChanged += MyMethod;
 EditorApplication.isPlaying = true;

MyMethod gets called only once, right before entering play mode.
I want it to be called when pause/stop play mode is triggered as long as my method is subscribed. But it seems like entering playmode, for some reason, removes MyMethod from subscription?

If I reverse the order:

EditorApplication.isPlaying = true;
EditorApplication.playmodeStateChanged += MyMethod;

It doesn’t get called AT ALL!

Script that has MyMethod is not a MonoBehaviour, it is a static class. Nothing in my project uses EditorApplication.playmodeStateChanged other than mentioned line of code.

What am I doing wrong?

I have the same problem, it will get called when it changes from “not playing” to “playing”, but never the other way round. I guess it maybe has something to do with the editor clearing the managed space when entering playmode, thus effectively removing the instances of the playmode state changed handlers, so they are destroyed and never to be seen again.

1 Like

How about;

[InitializeOnLoad]
public class MyTool
{
    static MyTool()
    {
        EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
    }

    private static void PlaymodeStateChanged()
    {
        Debug.Log("LOL");
    }
}
3 Likes

That’s how I solved it.
Putting [InitializeOnLoad] over the script makes the subscriptions last through playmode.
Though I had to spend quite some time researching to find that solution. Unity Formus or Answers never provide any support for me. :frowning:

Nicely done unity, another well documented feature!

3 Likes

Well…You just helped me not waste my time on that.