- Home /
Detecting moment when GameObiect is created in hierarchy.
Hi, I need to know moment when any new GameObject is added to hierarchy (from project window, CtrlD, code etc). I know about EditorApplication.hierarchyWindowChanged but it gives me no informatian what type of change it was. In general i want sth like "SuperHelpfulEditorClass.onGameObiectCreated". Any ideas?
A don't think that exists, but you can always count all the gameobjects in scene when EditorApplication.hierarchyWindowChanged and check if that number is higher than it was before ;)
Answer by Jessespike · Sep 16, 2016 at 06:26 PM
As iabulko suggested, use hierarchWindowChange and keep track of the number of objects.
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class SuperHelpfulEditorClass {
public delegate void HierarchyChangeAction(GameObject go);
public static event HierarchyChangeAction onGameObjectCreated;
static int objectCount = 0;
static SuperHelpfulEditorClass()
{
EditorApplication.hierarchyWindowChanged += OnHierarchyWindowChanged;
}
static void OnHierarchyWindowChanged () {
GameObject[] objects = (GameObject[]) Resources.FindObjectsOfTypeAll (typeof (GameObject));
if (objects.Length > objectCount)
{
GameObject go = Selection.activeGameObject;
if (onGameObjectCreated != null)
onGameObjectCreated(go);
}
objectCount = objects.Length;
}
}
New GameObjects are selected by default, not sure how reliable this is, so it might have to change. The event can be used like this:
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class ShowCreatedGameObjectName {
static ShowCreatedGameObjectName()
{
SuperHelpfulEditorClass.onGameObjectCreated += OnGameObjectCreated;
}
static void OnGameObjectCreated(GameObject go)
{
Debug.Log("GameObject was created.\nGameObject.name = " + go.name);
}
}
Thanks for answer! (I'm xenix2012 but from another account because I can't log out from this one on my phone :/). I've did this same (and I've added onObjectDestroyed event too) BUT performance of FindObjectOfTypeAll is... horrible. If anyone has any diffrend idea I would be glad to hear it :)