I have parent gameobject which has many child game objects. How do i get a random child game object from those lists of gameobjects.
Transform.childCount, Transform.GetChild(), and Random.Range() should have you covered.
2 Likes
Transform[] childs = gameObject.GetComponentsInChildren<Transform>();
GameObject randomObject = childs[Random.Range(0,childs.Length)];
I’m not sure just posting the complete solution to a trivial problem is the right approach, that’s why I didn’t.
Cannot implicitly convert type UnityEngine.Transform[ ]' to
UnityEngine.GameObject[ ]’
I am getting above error when trying above code
Yeah, here you go:
Transform[] childs = (Transform[]) gameObject.GetComponentsInChildren<Transform>();
GameObject randomObject = (GameObject) ((Transform)childs[Random.Range(0,childs.Length)]).gameObject;
2 Likes