LoginSignup
11
13

More than 5 years have passed since last update.

[Unity]子オブジェクトをTransformで取得

Posted at

オブジェクトの子を取得する方法は検索すれば色々な方法が出てくると思いますが、メモとして。
今回はMeshRendererを持つ子オブジェクトにBoxColliderコンポーネントを追加するスクリプトを作成します。

子オブジェクトの取得

var childTransform = GameObject.Find("RootObject").transform;

foreach (Transform child in childTransform.transform)
{
    if (null != child.GetComponent<MeshRenderer>())
    {
        if(null == child.GetComponent<BoxCollider>())
        {
            Debug.Log(child.name);
            child.gameObject.AddComponent<BoxCollider>();
        }
    }
}

GameObject.Find("RootObject")の所は

public Transform rootObject;

のようにして、インスペクタからアタッチしても良いです。
FindとForeachを使用しているので、処理時間はかかるかもしれません。

全ての子(孫)オブジェクトを取得

var childTransform = GameObject.Find("RootObject").GetComponentsInChildren<Transform>();

foreach (Transform child in childTransform)
{
    if (null != child.GetComponent<MeshRenderer>())
    {
        if(null == child.GetComponent<BoxCollider>())
        {
            Debug.Log(child.name);
            child.gameObject.AddComponent<BoxCollider>();
        }
    }
}

GetComponentsInChildrenですべての子コンポーネントを取得します。

childTransformは配列で受け取ります。

11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13