GetComponentInChildren

I have this

public GameObject obj;
public Rigidbody rigid;
public Transform trans;

// Use this for initialization
void Start () {
	rigid = obj.GetComponent<Rigidbody> ();
	trans = obj.GetComponentInChildren<Transform> ();
}

// Update is called once per frame
void Update () {
	
}

And I want to pick up the obj CHILD transform but the unity only picks up the object’s parent transform

99287-sem-titulo.png

“GetComponentInChildren” is a badly choosen name for what it does. It doesn’t only search through the immediate children of the object but also on the parent as well as any deeply nested children.

The order is like this:

  • First search on the parent
  • Then it does a depth-first search through the hierarchy of the parent

So basically the way the object and it’s childs appear in the hierarchy window from top to bottom.

GetComponentInChildren<Transform>() will always be equal to GetComponent<Transform>()since every gameobject has a Transform component.

If you want to access the immediate children you simply would use transform.GetChild(0) for the first child. You may want to check “childCount” before accessing a child to avoid an index out of bounds error if there is no child.

Another way is to use the name of the child by using transform.Find("childname"). See Transform.Find for more information. Note that Transform.Find is not the same as GameObject.Find. Transform.Find will only search the immediate children of the given transform (and if the string contains a “path” it will traverse downwards as well). For example transform.Find("immediateChild/nestedChild") will return the nestedChild inside immediateChild.