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

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;   
     }
 }