using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace TyphoonUI { public class HierarchyIndex : List, IComparable { public int CompareTo(HierarchyIndex other) { for (int i = 0; i < this.Count && i < other.Count; i++) { var a = this[i]; var b = other[i]; if (a != b) { //继续比较 return a.CompareTo(b); } } return this.Count.CompareTo(other.Count); } } public static class Extension { //获取组件层级路径 public static int GetComponentIndex(this Component component) { var coms = component.gameObject.GetComponents().ToList(); return coms.IndexOf(component); } public static HierarchyIndex GetHierarchySiblingIndices(this GameObject target) { var stack = new Stack(); var node = target.transform; while (node != null) { var index = node.GetSiblingIndex(); stack.Push(index); node = node.parent; } var result = new HierarchyIndex(); while (stack.Count > 0) { result.Add(stack.Pop()); } return result; } public static string GetHierarchyIndexString(this GameObject target) { var result = string.Empty; var node = target.transform; while (node != null) { result += node.GetSiblingIndex().ToString().PadLeft(4, '0'); node = node.parent; } return result; } public static string GetHierarchyPath(this GameObject target) { var result = $"{target.gameObject.name}"; var node = target.transform; while (node.parent != null) { result = $"{node.parent.name}/{result}"; node = node.parent; } return result; } } }