[Unity6] 子オブジェクトを取得する方法4選 (GetChild, Find, foreach, GetComponentsInChildren)

(2025/02/19)
[Unity6] 子オブジェクトを取得する方法4選 (GetChild, Find, foreach, GetComponentsInChildren)

開発環境
  • Unityのバージョン : 6000.0.36f1
  • 方法1 Transform.GetChild(index)を使う

    ・指定したインデックスの子オブジェクトを取得します。
    ・子オブジェクトは、Hierarchyビューでの順番(0から始まる)でインデックスが付けられます

    using UnityEngine;
    
    public class SampleScript : MonoBehaviour
    {
        void Start()
        {
            // 最初の(インデックス0の)子オブジェクトを取得
            Transform firstChild = transform.GetChild(0);
    
            // 最初の(インデックス0の)子オブジェクトの名前をコンソールに出力
            Debug.Log("First child: " + firstChild.name);
    
            // 全ての子オブジェクトの名前を出力
            for (int i = 0; i < transform.childCount; i++)
            {
                Transform child = transform.GetChild(i);
                Debug.Log("Child " + i + ": " + child.name);
            }
        }
    } 
    


    方法2 Transform.Find(name)を使う

    ・指定した名前の子オブジェクトを検索します。
    ・同じ名前の子オブジェクトが複数存在する場合、最初に見つかった子オブジェクトのみが返されます。
    ・子階層より深い孫階層以下のオブジェクトも取得できます。

    using UnityEngine;
    
    public class SampleScript : MonoBehaviour
    {
        void Start()
        {
            // "Cube" という名前の子オブジェクトを検索
            Transform child = transform.Find("Cube");
    
            if (child != null)
            {
                Debug.Log("Found child: " + child.name);
            }
    
            // "Cube (1)"という名前の孫オブジェクトを検索。
            Transform grandChild = transform.Find("GameObject/Cube (1)");
    
            if (grandChild != null)
            {
                Debug.Log("Found grand child: " + grandChild.name);
            }
        }
    } 
    


    方法3 foreach (Transform child in transform)を使う

    ・foreachループで直接子オブジェクトを反復処理できます。

    using UnityEngine;
    
    public class SampleScript : MonoBehaviour
    {
        void Start()
        {
            // 全ての子オブジェクトに対して処理を行う
            foreach (Transform child in transform)
            {
                //すべての子オブジェクトの名前を出力
                Debug.Log("Child name: " + child.name);
            }
        }
    }
    


    方法4 GetComponentsInChildren<T>()を使う

    ・自分自身とすべての子オブジェクト(孫オブジェクト以下も含む)から、指定した型のコンポーネントを取得します。
    ・取得したコンポーネントの配列を返します。

    using UnityEngine;
    
    public class SampleScript : MonoBehaviour
    {
        void Start()
        {
            // 全ての子オブジェクト(自分自身、孫オブジェクトも含む)から Transformコンポーネントを取得
            Transform[] transforms = GetComponentsInChildren<Transform>();
    
            foreach (Transform transform in transforms)
            {
                // 全ての子オブジェクト(自分自身、孫オブジェクトも含む)の名前を出力
                Debug.Log("Transforms found on: " + transform.gameObject.name);
            }
        }
    }