using System.Linq; using UnityEngine; namespace AZTECHWB.Extensions { public static class TransformExtension { public static T GetOrAddComponent(this Transform root) where T : Component { if (root.TryGetComponent(out var result)) { return result; } return root.gameObject.AddComponent(); } public static T Find(this Transform root, string name) where T : UnityEngine.Component { for (int i = 0; i < root.childCount; ++i) { var child = root.GetChild(i); if (child.TryGetComponent(out var result)) { if (child.name == name) { return result; } } result = child.Find(name); if (result != null) { return result; } } return null; } public static T GetComponentInChildren(this Transform root, string name) where T : Component { for (int i = 0; i < root.childCount; ++i) { var c = root.GetChild(i); if (c.TryGetComponent(out var result)) { if (c.gameObject.name == name) return result; } result = c.GetComponentInChildren(name); if (result != null) { return result; } } return null; } public static bool TryGetComponentInChildren(this Transform root, string name, out T result) where T : Component { if (root.TryGetComponent(out result)) { if (result.name.Equals(name)) { return true; } } for (int i = 0; i < root.childCount; ++i) { var children = root.GetChild(i); if (children.TryGetComponent(out result)) { if (result.name.Equals(name)) return true; } if (children.TryGetComponentInChildren(name, out result)) { if (result.name.Equals(name)) { return true; } } } return false; } public static bool TryGetComponentsInChildren(this Transform root, out T[] result) where T : Component { result = root.GetComponentsInChildren(); if (result != null && result.Length != 0) { return true; } return false; } public static bool TryGetComponentInChildren(this Transform root, out T result) where T : Component { if (root.TryGetComponent(out result)) { return true; } for (int i = 0; i < root.childCount; ++i) { var children = root.GetChild(i); if (children.TryGetComponent(out result)) { return true; } if (children.TryGetComponentInChildren(out result)) { return true; } } return false; } public static bool TryGetComponentInParent(this Transform root, out T result) { var curr = root.parent; while (curr != null) { if (curr.TryGetComponent(out result)) { return true; } curr = curr.parent; } result = default(T); return false; } public static bool Contains(this Transform root, T target) where T : Component { var comps = root.GetComponentsInChildren(); if (comps.Contains(target)) { return true; } return false; } public static Vector3 GetMeshCenter(this Transform root) { { Renderer[] renderers = root.GetComponentsInChildren(true); if (renderers == null || renderers.Length == 0) { return Vector3.zero; } // 첫 번째 Renderer의 bounds로 초기 바운딩 박스를 설정 Bounds combinedBounds = renderers[0].bounds; // 나머지 Renderer들의 bounds를 combinedBounds에 포함시킴 for (int i = 1; i < renderers.Length; i++) { combinedBounds.Encapsulate(renderers[i].bounds); } // 결합된 바운딩 박스의 중심점을 반환 return combinedBounds.center; } } } }