※GameObject.Find~系、GameObject.Get~系は重いのでなるべく使わないようにする
https://docs.unity3d.com/ScriptReference/GameObject.Find.html
private GameObject cube;
void Start()
{
cube = GameObject.Find("Cube");
}
※GameObject.Find は全オブジェクトを走査するので重い。
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html
private GameObject cube;
void Start()
{
cube = GameObject.FindGameObjectWithTag("cube");
}
https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
private GameObject[] cubes;
void Start()
{
cubes = GameObject.FindGameObjectsWithTag("cube");
}
※親要素から子要素を取得する場合は、子要素が非アクティブでも取得可能
cf. http://kimama-up.net/unity-find/
https://docs.unity3d.com/ScriptReference/Transform.Find.html
private GameObject cube;
void Start()
{
cube = transform.Find("Cube").gameObject;
}
private List<GameObject> childCubes = new List<GameObject>();
void Start()
{
if (transform.childCount == 0) return;
foreach (Transform childTrans in transform)
{
childCubes.Add(childTrans.gameObject);
}
}
cf. http://kazuooooo.hatenablog.com/entry/2015/08/07/010938
すべての子要素を取得 にタグ判定を入れただけ
private List<GameObject> childCubes = new List<GameObject>();
void Start()
{
if (transform.childCount == 0) return;
foreach (Transform childTrans in transform)
{
if(childTrans.gameObject.tag == "cube")
{
childCubes.Add(childTrans.gameObject);
}
}
}
parent: 一つ上の要素
https://docs.unity3d.com/ScriptReference/Transform-parent.html
private GameObject childObj;
void Start()
{
childObj = GameObject.Find("Child");
childObj.transform.parent.gameObject.SetActive(false);
}
root: 一番上の要素
https://docs.unity3d.com/ScriptReference/Transform-root.html
private GameObject childObj;
void Start()
{
childObj = GameObject.Find("Child");
childObj.transform.root.gameObject.SetActive(false);
}