GameObjects
do not have children per-se. When we talk about children to a GameObject
we are actually referring to the children of the Transform
component (that all GameObjects
have). This means that you have to use the Transform
component to access the children:
void Start() {
// All GameObjects have a transform component built-in
foreach(Transform child in this.transform) {
GameObject obj = child.gameObject;
// Do things with obj
}
}
The reason you can't use GetComponentsInChildren<T>()
to get the children is simply because that is not the functionality of that function. That function (like the name says) is used to get components from children (not the children themselves). For example (taken from Unity documentation):
void Start()
{
var hingeJoints = GetComponentsInChildren<HingeJoint>();
foreach (HingeJoint joint in hingeJoints)
joint.useSpring = false;
}
However I guess you can technically use this function to get all children:
void Start()
{
// This only works because GameObjects always have the Transform component,
// and there can only be 1 transform component per GameObject
var transforms = GetComponentsInChildren<Transform>();
foreach (Transform transform in transforms) {
GameObject obj = transform.gameObject;
// Do something with obj
}
}