Strange code Debugging

Hi everyone!
I’am just trying to move some children to an other gameObject, but only half was been transfered correctly!?

Here my code:

        print("old Child Count " + oldGameObject.transform.childCount);
        int i = 0;
        foreach(Transform child in oldGameObject.transform) {
            print("Moving child '" + i + "' to new");
            child.parent = newGameObject.transform;
            i++;
        }

and here the result:

old Child Count 6
Moving child '0' to new
Moving child '1' to new
Moving child '2' to new

And that all…

Somebody can explain that?

The method you used simply iterates from bottom to top. As you move the objects the count reduces and so as the index increases objects get missed out.

My method iterates from top to bottom using GetChild(index). (Explain how this for loop works with cnt>=0 ??)

using UnityEngine;
using System.Collections;

public class CHILDMOVE : MonoBehaviour {

	public GameObject oldGameObject;
	public GameObject newGameObject;

	void Start () {
		oldGameObject = gameObject;
		NewFunc ();
	 }
	
	void NewFunc () {
				print("old Child Count " + oldGameObject.transform.childCount);
        
				int blah = oldGameObject.transform.childCount;
				for(int cnt=blah-1; cnt>=0; cnt--)
				{
					print("LATEST old Child Count " + oldGameObject.transform.childCount + " " + cnt);
					oldGameObject.transform.GetChild(cnt).parent = newGameObject.transform;
				}
	}
}