Unityを触り始めてつまずいたGetComponentsInChildrenについて
GetComponentsInChildrenは親オブジェクトも取得してしまうので子オブジェクトのみ取得する方法
Test1.cs
using System.Linq;
public GameObject parent;//親オブジェクト
private void Start()
{
List<GameObject> child = new List<GameObject>(parent.GetComponentsInChildren<GameObject>())
.Select(item => item.gameObject)//TransformをGameObjectに変換
.Skip(1)//親オブジェクトをスキップ
.ToList();//Listに変換
}
見やすくするために改行しているが、Linqを使えば1行で取得できる
Unityを使い始めたころはこのように書いていた
Test2.cs
public GameObject parent;//親オブジェクト
private void Start()
{
GameObject[] child = new GameObject[parent.transform.childCount];//子オブジェクトの数で初期化
for(int i = 0; i < child.Length; i++)
{
child[i] = parent.transform.GetChild(i).gameObject;//子オブジェクト取得
}
}