Question on Using a Foreach Loop on Nested Children

Hello everyone, I was trying to setup a simple foreach loop that iterates though each child Transform of a GameObject but I ran into a problem:

The loop only finds the immediate child / children of the gameObject that runs it. So, if you have immediate children like: A → B,C,D would find 3 children), however with nested children like: A → B → C → D will only yield 1 child.

Here is the loop in question (and I belive I’ve seen this a few times before which lead me to thinking it would work in the first place:

		foreach (Transform trans in gameObject.transform)
		{
			Debug.Log ("found a child transform");
		}

Is this the expected behavior / Am I doing something wrong? (My guess is yes to both questions…). I know I can just make a transform array and use that, but doing it this way just seemed cleaner. Any clarification is appreciated.

That’s the expected behaviour, this post is very relative, you’ll find the answers you need there I suppose :slight_smile:

Hope that helps, gl! :smiley: