How to properly call a method when a GameObject is Destroyed ?

Hi !
I’m trying to make an Editor tool in which when the user delete a GameObject, some corresponding assets will be destroyed. At first, I was using OnDestroy(). I wanted it to be used only when deleting manually so I used this : if (EditorApplication.isPlayingOrWillChangePlaymode == false && Time.frameCount != 0 && Time.renderedFrameCount != 0 && UnityWantsToQuit == false)
Which worked just fine. Then I learned that OnDestroy() is not called if the GameObject was not enabled before (so if I disable it in Edit Mode, then enter Play Mode then come back to Edit Mode, it won’t be called).

So I made a script to spawn a seperate GameObject when the GameObjects that the user will delete are disabled (let’s call it the AssetDestroyer). It stores the corresponding assets, and checks if the gameobjects were deleted to then delete the right assets, but I found an other problem. As I used the same “if” statement as OnDestroy() to use it only when disabling manually, I found that Time.frameCount and Time.renderedFrameCount are way above 0 after reloading scripts (after changing a script and going back to Unity). The idea was to spawn the AssetDestroyer only when necessary but I can’t do that since OnDisable() isn’t called only when disabling manually, so now I’m stuck with the AssetDestroyer being always spawned automatically. It ends up better to just have an added GameObject there at all time.

It is still the best way I’ve found to achieve my goal but do you know any better way ? Is there a way to check when the user is disabling a GameObject manually ? Or is there a way to check when the user is deleting a GameObject manually, including when it has not been enabled ?

Thank you very much for your answers !

Use [ExecuteInEditMode]. I’ve tested OnDisable and OnDestroy triggers even when both the script and the gameobject is inactive. Just handle these callbacks.