- Home /
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.
Answer by ThePersister · Oct 30, 2014 at 09:47 AM
That's the expected behaviour, this post is very relative, you'll find the answers you need there I suppose :) http://answers.unity3d.com/questions/10417/how-can-i-access-the-children-of-a-transform.html
Hope that helps, gl! :D
Your answer
Follow this Question
Related Questions
C# Child GameObject Disabled Script SetActive(false) 1 Answer
C# GameObject.FindGameObjectsWithTag Children 1 Answer
Problem with player movements 1 Answer
How to make specific text in a string array Bold C# 2 Answers
What is the best way to grab and move the immediate children of a GameObject. 1 Answer