-1
\$\begingroup\$

I have a gameobject with a bunch of empty gameobjects as children that I want to use as spawn positions.

I want to loop through each of these positions and have a certain amount of probability that an object spawns.

How could I write a foreach loop that takes the parent object and loops through all its children like it would with an array?

\$\endgroup\$
5
  • 1
    \$\begingroup\$ What engine or tech stack are you using? \$\endgroup\$
    – DMGregory
    Mar 9, 2019 at 19:36
  • \$\begingroup\$ I'm using unity \$\endgroup\$ Mar 9, 2019 at 19:46
  • 1
    \$\begingroup\$ So presumably you read the documentation on the Unity Transform component to learn how to iterate its children? Where did you run into trouble applying this to your case? \$\endgroup\$
    – DMGregory
    Mar 9, 2019 at 19:49
  • \$\begingroup\$ Well your presumption was wrong, I couldn't find the documentation lol thank you very much. \$\endgroup\$ Mar 9, 2019 at 19:57
  • 1
    \$\begingroup\$ Next time, remember to search first - the very first Google result for "unity iterate child objects" includes this technique. Don't underestimate your ability to find your own answers! :) \$\endgroup\$
    – DMGregory
    Mar 9, 2019 at 20:04

2 Answers 2

3
\$\begingroup\$

By itself, the transform class implements the IEnumerable (with Transform as the generic type) interface, which allows you to use a foreach with a transform as the interable object. You could also use a normal for loop, using Transform.GetChild(int). Examples:

foreach(Transform child in transform)
{
    /// All your stuff with child here...
}

for(int i = 0; i < transform.childCount; i++)
{
    /// All your stuff with transform.GetChild(i) here...
}

Hope it helps.

\$\endgroup\$
0
\$\begingroup\$

A good coding practice would result in the following code:

[SerializeField]
GameObject gb;    //outside the function

foreach (Transform child in gb.transform)
{
    Debug.Log("Name Of Child " + child.transform.name);
}
\$\endgroup\$
1
  • \$\begingroup\$ What is it about this that you would consider to be an improvement over the existing answer, which also shows how to write this foreach loop? \$\endgroup\$
    – DMGregory
    Jan 18, 2023 at 20:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .