I’ve been able to find this question asked all over the place, but for some reason I haven’t been able to find a real answer. It’s so simple yet has only ever been explained in the vaguest, most cryptic ways possible (at least that I’ve found).
How do you access child GameObjects?
Not child Transforms, not components of child GameObjects, just plain child GameObjects. By this I mean simply the immediate children, not an extensive hierarchy of them (grandchildren).
I keep seeing this posted everywhere as an answer, but it’s not what the question is asking:
for (var child : Transform in transform)
{
child.DoSomething;
}
I tried adjusting this using “GameObject in gameObject” instead, but it doesn’t work. Is there something simple that I’m missing? I can’t think of anything I would need to add or change. Forgive me if this is a stupid question, I’m just confused after all the strangely obscure answers I’ve read.
Class GameObject does not inherit IEnumerable so you can’t loop through it with a for-each loop. Transform is an IEnumerable and that’s why it can be for-eached.
Luckily you can refer to the connected GameObject through the Transform.
for (var child : Transform in transform)
{
child.gameObject.DoSomething;
}
Looking at this API document you can see that anything that extends the Component class (basically anything that can be added to a GameObject: MonoBehaviours, Rigidbodies, Colliders) by default has readily made public variables for your convenience for referring to many other components that could exist in that gameObject.
You can refer a GameObject’s transform by gameObject.transform or to a Collider of a gameObject through it’s gameObject.collider etc… Heck, you can even refer to the gameObject itself by going back and forth as many times as you like if you want to write long and nonsensical code: this.gameObject.transform.gameObject.transform.gameObject.transform.gameObject…
Of course, if there’s no collider attached to the gameObject, the gameObject.collider will be null
The point you have to understand is, that there is nothing like a child-gameobject. A GameObject has no functionality besides:
giving the object a name, tag, layer.
hold the information if the GameObject is active and if it’s static or not.
provide a container for components
That’s all. The hierarchy you see in the scene view is actually a hierarchy of Transform components. The GameObject class is actually the most useless class in unity as it covers almost no functionality. On the other side it’s the most important class as it is required as “glue” between components. In 90% of all cases you don’t need to work with GameObject references as most data and functionality is implemented through components.
You only need GameObject references if you want to activate / deactivate an object, destroy a complete gameobject or change it’s name, tag, layer.