オブジェクトの子を取得する方法は検索すれば色々な方法が出てくると思いますが、メモとして。
今回は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は配列で受け取ります。