Question by
LevonVH · Nov 26, 2019 at 01:23 PM ·
editoreditor-scripting
How to know if a component is removed in Editor
I am making a custom editor plugin. To accomplish my purpose I need to know if a component is added or removed in the editor mode.
I used the OnValidate() method to be notified if the component is newly added to the scene or its state has been changed from the Editor. But I also need to have a callback in the Editor when the component is removed. For example, if some Monobehaviour extender is removed by the user in the Editor mode, I want it to receive a callback.
The problem is that OnDestroy() is not called in the editor mode. I cannot use the [ExecuteInEditMode] attribute either because I am making an extended version of MonoBehaviour which will be used instead of MonoBehaviour throughout the application. And so using [ExecuteInEditMode] would make a chaos in the Editor.
This is a super simple question which in my opinion should be resolved with a simple callback method provided by the MonoBehaviour. But after extensive research I am desperate. Can anyone help?
Comment
Answer by SlenderPaul · Jul 01, 2020 at 03:58 PM
Had the same Problem and It took me way to long to find an acceptable solution. At the end I figured out that, when you have a custom Editor for your component, its target property is null when OnDisable() is called and the Component was removed. This however won't work if you attach your component by dragging it to an object that's not open in the Inspector and then remove it with Undo.
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(ComponentThatCallsOnRemove))]
public class RomovalDetector : Editor
{
void OnDisable()
{
if(target == null)
{
Debug.Log("COMPONENT REMOVED!");
//Your [Action | Event | Exception | Whatever] here
}
}
}
$$anonymous$$y dude thank you VERY $$anonymous$$UCH ! You're a savior !