PlayModeStateChange EnteredPlayMode called multiple times

Any idea why enteredPlayMode gets called more than once when I play my empty scene with only this script in it?
Usually I get 2-3 logs.

[InitializeOnLoad]
public class GameModeEvents : MonoBehaviourSingleton<GameModeEvents>
{

    GameModeEvents()
    {
        EditorApplication.playModeStateChanged += playmodeStateChanged;
    }

    private void playmodeStateChanged(PlayModeStateChange playMode)
    {
        switch (playMode)
        {
            case PlayModeStateChange.EnteredPlayMode:
                //this gets called multiple times
                Debug.Log("entered playmode");
                break;

        }
    }
}

I suspect the I am subscribing multiple times when the constructor gets called? Moving the subscription into the Awake function seems to fix the multiple call issue, but cause some order issues for me…

You shouldn’t use the constructor in MonoBehaviour derived classes, precisely for the reason that you’re running into. The lifecycle of MonoBehaviour classes is not like a typical C# object lifecycle. Awake is meant as a replacement for a constructor in MB objects.

Usually, you would not attach editor events like these to a MonoBehaviour, and would instead use a POCO class with the InitializeOnLoad/Method attribute instead.

1 Like