Callback event when another component added to game object in editor

Is there a callback for a different component being added to a gameObject?

Scenario:

  1. Empty game object.
  2. Add example component “MyWidget” to empty game object.
  3. Drag an audio source onto the empty game object.
  4. Desire: Some callback on MyWidget that a component was added to the gameObject.

Concept:
In the above scenario, the idea would be instead of the OnValidate method maybe an OnComponentAdded method that is called back with the MonoBehavior (Audio Source in this case) that was added. This method obviously doesn’t exist, but I’m looking for something like this.

What I’ve tried:
I have created an execute in editor update loop that calls GetComponent<…> every second. It’s functional, but I don’t want to use this approach. Looking for an event driven alternative.

2 Likes

I see a similar question was asked in 2014: Event when component added or removed

This doesn’t quite address the inquiry. The (current simplified) goal is to detect when someone drags and drops an audio source onto a game object, I want an existing component on that game object to be able to react to that event. I’d like to support the native drag and drop of the audio source. While I can create a custom button and a custom workflow, that would still not support the native drag and drop audio source that I can tell or think of.

Perhaps you could make a custom inspector for an AudioSource and call the base one’s inspector, after first checking if this is new to you? You’d need a place to serialize the fact that you “know” this one, but you could just add a local Component with a boolean.

Hm. I just tested dragging an audio source onto a game object in my scene, and the inspector didn’t change. So, I don’t think that would trigger a callback.

It sounds like a creative approach, but doesn’t seem like a native callback solution. Is there any way to submit official feature requests? I think this would fit in with OnValidate type callbacks, creating a new OnComponentAdded type callback.

The Future of Unity Feedback Just says that feedback goes on the forums. But, doesn’t seem like this will be looked at. Hmm…

1 Like

Any other thoughts? How would I make this an official suggestion or feature request to Unity3d?

2 Likes

Second this. We need “OnComponentAdded/Removed” callbacks for ExecuteInEditMode classes to be more robust.

I have a component that needs to add listeners to another component if it exists, but obviously this is subject to change during the component’s lifetime if we’re in Edit Mode.

As a hacky workaround, you can use “OnEnable” and “OnDisable” to register the listeners then manually toggle the checkbox in the editor, but this isn’t acceptable for components that shouldn’t allow enable/disable conceptually.

2 Likes