Files
Studio/Assets/Scripts/XRLib/Extenstions/TransformExtension.cs
2025-05-25 14:19:35 +09:00

127 lines
3.9 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace XRLib
{
public static class TransformExtension
{
public static List<T> FindAll<T>(this MonoBehaviour root)
{
List<T> result = new List<T>();
if (root.transform.TryGetComponents<T>(out var value))
{
result.AddRange(value);
}
var childCount = root.transform.childCount;
for (int i = 0; i < childCount; ++i)
{
var childComponents = FindAll<T>(root.GetChild(i));
result.AddRange(childComponents);
}
return result;
}
static Transform GetChild(this MonoBehaviour root, int index)
{
return root.transform.GetChild(index);
}
public static void FindAll<T>(this Transform root, ref List<T> container)
{
if (root.TryGetComponents<T>(out var value))
{
container.AddRange(value);
}
var childCount = root.childCount;
for (int i = 0; i < childCount; ++i)
{
FindAll(root.GetChild(i), ref container);
}
}
public static List<T> FindAll<T>(this Transform root)
{
List<T> result = new List<T>();
if (root.TryGetComponents<T>(out var value))
{
result.AddRange(value);
}
var childCount = root.childCount;
for (int i = 0; i < childCount; ++i)
{
var childComponents = FindAll<T>(root.GetChild(i));
result.AddRange(childComponents);
}
return result;
}
public static T DeepFind<T>(this Transform root, string name) where T : Component
{
T result = default;
int count = root.childCount;
for (int i = 0; i < count; ++i)
{
var child = root.GetChild(i);
if (child.TryGetComponent<T>(out result))
{
if (result.name == name)
{
return result;
}
}
result = child.DeepFind<T>(name);
if (result != null)
{
break;
}
}
return result;
}
public static T Find<T>(this Transform root) where T : Component
{
T result = default;
if (root.Find<T>(ref result))
{
return result;
}
return result;
}
public static List<Transform> GetParents(this Transform root)
{
List<Transform> result = new List<Transform>();
var parent = root.parent;
while (parent != null)
{
result.Add(parent);
parent = parent.parent;
}
return result;
}
/// <summary>
/// T 가 나올때 까지 자식오브젝트를 순회한다. 여러개가 있다면 가장 먼저 발견된 것을 ref 로 내보낸다.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="root"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool Find<T>(this Transform root, ref T result) where T : Component
{
if (root.TryGetComponent<T>(out result))
{
return true;
}
var childCount = root.transform.childCount;
for (int i = 0; i < childCount; ++i)
{
if (root.GetChild(i).Find<T>(ref result))
return true;
}
return false;
}
public static bool TryGetComponents<T>(this Transform root, out T[] result)
{
result = root.GetComponents<T>();
return result.Length > 0;
}
}
}