Detect added/removed components in the editor on a given object

Say class “Foo” holds a list of class “Bar”.

I’m making an editor tool and I want it to be stupid simple. Basically I want to stop the user from manually modifying the amount of entries in the list in the inspector, and instead, populate it automatically whenever the user adds or remove a class “Bar” component on the object holding the class “Foo”.

Ideally, I’d like something like OnComponentAdded or OnComponentRemoved.

The current workaround that I found was to use the editor’s update method and check if the components have changed every frames. Thing is, I intend on having a lot of objects holding class “Foo” and I’m curious as to wether or not there’s a more efficient way.

Looking forward to hearing your solutions.

There’s OnValidate() which is called whenever data for a MonoBehaviour is changed in the inspector.

I’m attempting to go with that.

So far it’s triggering when the component is added, which is great. I’m adding the component to the list just fine. However OnValidate isn’t called when the component is removed.

I tried adding OnValidate to the class holding the list as well, hoping that when the user removes a class “Bar”, since the list changes its entry from class “Bar” to “Missing (Entry)”, that OnValidate would fire. No luck.

Any ideas how I could cover the OnComponentRemoved scenario?

I don’t know if you ever found an answer to this but I was trying to do something similar. The way I did it was to use OnDestroy().

[CustomEditor(typeof(CustomInspectorClass)
public class A_Class : Editor
{
void OnDestroy()
{
Debug.Log(“Component has been removed.”);
}
}

What if it inherits from monobehaviour and not editor?