Is there anyway I can be notified (possibly through some method/event raised) when a Component
is added to a GameObject
(and even child GameObject)?
I'd like to be notified(possibly in some editors scripts) when some events occurs in the editor for example:
Component
has been attached to a GameObject
instanceComponent
has been attached to a Prefab
GameObject
has become child of another GameObject
istanceIs this possible?If yes how?
EDIT
I found out a delegate for what concern parenting:EditorApplication.hierarchyWindowChanged
Accordingly to the doc it's called :
Called whenever the scene hierarchy has changed.
This is transform.parent changed, gameObject.name, creating a new game object, etc.
I still don't understand if there's a convinient way to understood which Object in the hierarchy has been changed.
The simplest way to get a child object of a game object in Unity is to use the Find method of the Transform class, i.e. transform. Find(“Child Object's Name”). This method will return the target child object which you can then perform various things with.
Finding child GameObject by index: You can get the first child of a GameObject with the GetChild function. GameObject originalGameObject = GameObject. Find("MainObj"); GameObject child = originalGameObject.
GetComponentsInChildren<Transform>(); is not an recursive method.
You can add a component to an object in your (editor-only) level-editing scene:
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
public class LevelEditorHelper : MonoBehaviour
{
LevelEditorHelper()
{
EditorApplication.hierarchyWindowChanged -= MyHierarchyChangedCallback;
EditorApplication.hierarchyWindowChanged += MyHierarchyChangedCallback;
}
private static void MyHierarchyChangedCallback()
{
Debug.Log("Hierarchy has changed");
}
}
#endif
Then within the callback you can access the current selected object (the added object will be the active selection):
GameObject activeObj = Selection.activeGameObject;
if(activeObj != null) {
...
And now you can check its parent to see if it matches whatever other object, and perform other checks to ensure this is actually the event you're interested in (remember it will be called for various other hierarchy changes too), then you can call another function to do whatever action you want.
Note: This won't work as-is for in-game scenes, if you edit your in-game scenes directly with your level-editor scripts then you'll need to use more careful placement of #if UNITY_EDITOR
and consider how to remove the unnecessary component (perhaps in Start
or at build-time if possible), or just leave it there doing nothing if you're happy with that. In my case my level editor is an editor-only scene, and it saves out a specific sub-set of the editor scene as a scene for use in-game.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With