Foreach skipping game objects.
Been fighting with some code all day, so I created a test example, and Foreach definately appears to be skipping items! I'm new to Unity and C# so could be something I'm doing, but I can't tell what!
I have 2 Game objects (Container1 and container2)
I placed 5 Game objects into container1 (GameObject1,Gameobject2,...)
I added the following script to container 1:
void Start()
{
GameObject newParent = GameObject.Find("Container2");
foreach (Transform child in transform)
{
child.parent = newParent.transform;
}
}
And after running this Object1,object3, and object5 are moved to Container2
Object2 and Object4 remain in container1
the code is fine, you will need some extra debugging to check if the foreach is really only looping 3 times also use a loop next to it and test if with the for loop it does work
Hi xxmariofer, could you give me a pointer as to what would help, like I say I'm quite new to unity and to c#!
add all this debugging
for(int i = 0; i < transform.childCount; i++)
{
Debug.Log("Number of childs: " + i);
}
foreach (Transform child in transform)
{
Debug.Log(child);
}
If I add a Debug.log line within the loop it logs 3 time. Again suggesting it is the loop that is skipping (as opposed to the parent change failing)
It os hard to tell i cant reproduce the issue fill free to upload a project but i bet the issue is somewhere else
Answer by Hellium · Aug 06, 2020 at 08:40 PM
You are modifying the collection while looping through it. Either store the children in an array or loop in from last to first
void Start()
{
GameObject newParent = GameObject.Find("Container2");
for(int i = transform.childCount - 1 ; i >= 0 ; --i)
{
transform.GetChild(i).parent = newParent.transform;
}
}