Is there a way to detect "On Component Attach" and "On Component Remove"??

Hello,

I want to is there a “on component attach or remove” that I can use? Most importantly, I want to be able to force the things I do in those two moments ONLY IN the “Editor Time”.

—Editor Time (Didn’t hit play button) —

Right after Adding a component “custom class” ==> ( Debug.Log (“Hi”))
Right after Removing a component “custom class” ===> ( Debug.Log (“Bye”))

—Run Time ( Pressed the play button) –

Right after Adding a component “custom class” ===> ( // DONT DO ANYTHING)
Right after Removing a component “custom class” ===> ( // DONT DO ANYTHING)

Thanks in advance

Here is a simpler and more performant method than the other answers have stated.

MonoBehaviour.Reset() runs on component attach in the editor.

If the script is tagged with [ExecuteInEditMode], MonoBehaviour.OnDestroy() will run when the component is removed from the GameObject. To make sure you’re in edit mode (since OnDestroy also runs in play mode), use Application.isEditor.

You can do a counter of components.
Remember put the attribute [ExecuteInEditMode]
But, there is not a beautiful way.
Look this example:

    private Component[] _components;
    private int _actualLength;

    private void Start()
    {
         GetAllComponents();
         _actualLength = _components.Length;
    }

     private void Update()
     {
            //Do this is not apropiate, for the performance :/
             GetAllComponents();

            if(_components.Length > _actualLength)
            {
                  Debug.Log("Was attached a component");
                   _actualLength = _components.Length;
            }
            else if(_components.Length < _actualLength)
            {
                    Debug.Log("Was removed a component");
                   _actualLength = _components.Length;
            }
     }

     private void GetAllComponents()
     {
         _components = GetComponents(typeof(Component));
     }

And you can use two properties
“Application.isEditor” And “Application.isPlaying”

No, if you want to do something when a component is added you can do in the component Awake method but only for components where you can change the code.

Also to do things only in the editor you can use:

#if UNITY_EDITOR
//your code here
#endif