r0128 r0128 - 1 year ago 87
C# Question

How to reference the child of a game object via script

I know this is a bit of a stupid question, but how would I reference the child (a cube) of a game object via script(the script is attached to the gameObject). (the equivalent to something like GetComponent)

Answer Source

You can get the first child of a GameObject with GetChild.

GameObject originalGameObject = GameObject.Find("MainObj");
GameObject child = originalGameObject.transform.GetChild(0).gameObject;

You can get other childs by using 1,2,3 and ...depending on the number of the child.

If all you want is the script attached to the child then use:

MyScript childScript = originalGameObject.GetComponentInChildren<MyScript>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download