OnDestroy in editor

Using Unity 5.4.1f1.

I’m trying to use OnDestroy() in a Monobehaviour with [ExecuteInEditMode] to detect when it is being deleted in the scene or removed from the GameObject (which is working fine).

However, the OnDestroy event is also called when the scene changes and I’ve had no success using Application.isLoadingLevel (also it seems to be deprecated without a working replacement).

Is there some way to do this? Is it possible to check if a scene is being loaded using SceneManager.LoadSceneAsync (which is what the documentation says to use) or will that just cause a scene to load whenever I call it?

A workaround is to check for Time.timeSinceLevelLoad != 0.
The time gets set to zero once a scene loads, including when you press play.

Two steps to detect objects destroyed in Edit mode.
Create a global state manager (e.g. PlayModeStateManager.cs) that tracks the current state of the editor:

[InitializeOnLoadAttribute]
public static class PlayModeStateManager {
    public static PlayModeStateChange PlayState;

    // register an event handler when the class is initialized
    static PlayModeStateManager () {
        EditorApplication.playModeStateChanged += LogPlayModeState;
    }

    private static void LogPlayModeState(PlayModeStateChange state) {
        PlayState = state;
    }
}

Then in your MonoBehavior do this check in OnDestroy:

void OnDestroy() {
    if (!EditorApplication.isPlayingOrWillChangePlaymode &&
        PlayModeStateManager.PlayState == PlayModeStateChange.EnteredEditMode) {
        // do the destroy logic
    }
}

I found that this method works on new Unity versions (2019.4):

 private void OnDestroy()
        {
#if UNITY_EDITOR
            if (!UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
            {
                if (Time.frameCount != 0 && Time.renderedFrameCount != 0)//not loading scene
                {
                    if (componentToDestroy != null)
                        DestroyImmediate(componentToDestroy);
                }
            }
            else
#endif
            {
                if (componentToDestroy != null)
                    Destroy(componentToDestroy);
            }
        }