Foreach loop not going through all elements
Hello!
I am having an issue with this piece of code:
foreach (Transform child in transform)
{
if (child.tag == "Grass")
{
child.transform.parent = grassList.transform;
}
if (child.tag == "Swamp")
{
child.transform.parent = swampList.transform;
}
if (child.tag == "Mountain")
{
child.transform.parent = mountainList.transform;
}
}
In theory it should go through every child in the current gameobject, and assign them their proper parents, however, it is only partially doing so. If the foreach loop is run several times (Through the update function, or manually calling it), it eventually manages to assign the correct parent to all the children.
Is there any way for the foreach loop to actually get all the children in one go? Mind you, we are talking about 100+ gameobjects at once.
Answer by Lolerooz · Jul 16, 2018 at 12:32 PM
Solved It!
Turns out that using a Foreach loop when you are removing elements from a list is not the best idea, as this causes it to skip every other child, resulting in only odd children to be parented. the solution to this it to create a copy outside of the foreach loop, and then accesing it from the loop.
The resulting code looks like this:
void SetParents() {
//Creates the List
List<Transform> childrenList = new List<Transform>();
//Adds all children to the list
foreach (Transform childTrans in transform)
childrenList.Add(childTrans);
//Goes through the list assigning parents
foreach (Transform childTrans in childrenList) {
if (childTrans.tag == "Grass")
{
childTrans.transform.parent = grassList.transform;
}
if (childTrans.tag == "Swamp")
{
childTrans.transform.parent = swampList.transform;
}
if (childTrans.tag == "Mountain")
{
childTrans.transform.parent = mountainList.transform;
}
}
}