unity/유니티 초보

Unity - 자식 Component 찾는 방법

rimugiri 2023. 1. 12. 21:52
728x90
public static T FindChild<T>(GameObject oj, string name = null) where T : UnityEngine.Object
{
    if (oj == null)
        return null;

    //첫번째 방법
    for (int i = 0; i < oj.transform.childCount; i++)
    {
        Transform transform = oj.transform.GetChild(i);
        if (transform.name == name)
        {
            T component = transform.GetComponent<T>();
            if (component != null)
                return component;
        }
    }

    //두번째 방법
    foreach(T component in oj.GetComponentsInChildren<T>())
    {
        if (component.name == name)
            return component;
    }
   
    return null;
}
728x90