How to Get Nth Son of a GameObject?

Is there a better way than:

GameObject GetSonByIndex(GameObject obj, int index)
{
  int i = 0;
  foreach(Transform tfm in obj.transform)
  {
    if(i == index)
      return tfm.gameObject;
    i++;
  }
  reutrn null;
}

Have you tried

var childCount : int

Or

IsChildOf (parent : Transform) : bool

Depending on why you need to check what child, you could use a tag system. What i like to do is set the tag on a condition like when its made a child or on start. Then you can find any object by tag with the compare tag function. :idea: :smile:

Sorry,what I want is to Get a son, not to Check a son.
Both “papa.childCount” and “IsChildOf(papa)” can’t help to “return the Nth son”(at least i don’t know how…).
Tag is only 32bit. and
if a GameObject has 33 sons, This method won’t work i think.

Getting a child object by its position in the list is not usually a good idea because the ordering of the child objects is not guaranteed. If you need to access specific child objects, it is best to give them all unique names and retrieve them with transform.Find:-

var childIndex: int;
var child = transform.Find("Child" + childIndex);
1 Like