Created
June 11, 2021 23:31
-
-
Save austinbossetti/978f1374fbb056b2265b55debcc8a8b6 to your computer and use it in GitHub Desktop.
Unity Hierarchy Changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Linq; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| using UnityEditor; | |
| [InitializeOnLoad] | |
| public static class HierarchyChangeTest | |
| { | |
| static List<HierarchyObject> _prevHierarchy; | |
| public static event Action<IEnumerable<HierarchyObject>, IEnumerable<HierarchyObject>> ObjectsInHierarchyThatChanged; | |
| static HierarchyChangeTest() | |
| { | |
| var hierarchy = GameObject.FindObjectsOfType<GameObject>().ToList(); | |
| _prevHierarchy = hierarchy.ConvertAll(t => new HierarchyObject(t, t.name, t.GetInstanceID())); | |
| EditorApplication.hierarchyChanged += EditorApplication_hierarchyChanged; | |
| } | |
| private static void EditorApplication_hierarchyChanged() | |
| { | |
| var newHierarchyGameObjects = GameObject.FindObjectsOfType<GameObject>().ToList(); | |
| var newHierarchy = newHierarchyGameObjects.ConvertAll(t => new HierarchyObject(t, t.name, t.GetInstanceID())); | |
| if(_prevHierarchy != null) | |
| { | |
| var prevHierarchyIds = _prevHierarchy.Select(t => t.GameObject.GetInstanceID()); | |
| var newHierarchyIds = newHierarchy.Select(t => t.Id); | |
| var deletedIds = prevHierarchyIds.Except(newHierarchyIds); | |
| var addedIds = newHierarchyIds.Except(prevHierarchyIds); | |
| var deleted = new List<HierarchyObject>(); | |
| foreach(var item in deletedIds) | |
| { | |
| var obj = _prevHierarchy.Find(t => t.Id == item); | |
| deleted.Add(obj); | |
| } | |
| var added = new List<HierarchyObject>(); | |
| foreach(var item in addedIds) | |
| { | |
| var obj = newHierarchy.Find(t => t.Id == item); | |
| added.Add(obj); | |
| } | |
| Debug.Log("deleted: " + string.Join(", ", deleted.Select(t => $"{t.Name} ({t.Id})"))); | |
| Debug.Log("added: " + string.Join(", ", added.Select(t => $"{t.Name} ({t.Id})"))); | |
| ObjectsInHierarchyThatChanged?.Invoke(deleted, added); | |
| } | |
| _prevHierarchy = newHierarchy; | |
| } | |
| public struct HierarchyObject | |
| { | |
| public GameObject GameObject; | |
| public string Name; | |
| public int Id; | |
| public HierarchyObject(GameObject gameObject, string name, int id) | |
| { | |
| GameObject = gameObject; | |
| Name = name; | |
| Id = id; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment