Foreach statement - Transform myvar in transform

I’m a little confused as to how this works.

foreach(Transform weapon in transform)
            if(weaponIndex == currentWeapon)

I’ve got it working. I just don’t understand how! :slight_smile:
it is iterating through the parent’s transform - that’s clear enough. But how does the parent’s transform know that there are children, each with their own transforms, and these ‘belong’ to the parent’s own transform?
I’m just a bit confused how the parent transform seems to be ‘storing’ the transforms for the children, too.


Hi AJMeyer,

Unfortunately, that’s Unity’s big secret. And since most parts of Unity are not open-source, so we often do not know what is going on behind the scenes. That is also the case here.

We know about this “children” feature because of the description in the API: “They also support enumerators so you can loop through children using”.

In the Transform class, there is very likely something implemented like this:

See also:

Thanks @Nina !

That helps. I was expecting to have to do something like find/get components/objects in children, of type transform, and then add these to a list or array, and us that for my foreach loop. So it was a cool surprise to find out that somehow all the child transforms are known by the parent transform.

The reason I asked is that I’m interested to know if there are other such examples. Or is transform the only one (perhaps on account of it being something that all game objects have)?

thanks for your reply in any case! And for your attention to my learning journey.

That’s a good question. At the moment, only the Transform class is coming into my mind. In other cases, we use arrays or lists. :confused:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.