Problem transferring children to a new parent

Hi

I’m trying to transfer all the children of an object to a new parent. The code below does not transfer all the items, it is skipping over some of them (explanation below)

	// Loop through all the children in old_parent and move them to new_parent
	foreach (Transform child in old_parent.transform) {
		Debug.Log("moving object: " + child.name);
		child.SetParent(new_parent.transform, false);
	}

However if I comment out the line changing the Parent, it does loop over every child

		// Loop through all the children in old_parent and move them to new_parent
		foreach (Transform child in old_parent.transform) {
			Debug.Log("moving object: " + child.name);
//			child.SetParent(new_parent.transform, false);
		}

I do get the name of all the children.

I think this is the typical problem when you change the list (or array) you are iterating over. In pseudocode

original list [A, B, C]
the loop starts
  go fetch the element at position 0 (A)
  remove it, now list is [B, C]
next iteration of the loop
  go fetch element at position 1 (and now this is C and not B)
  the list is 

I usually solve this problem iterating backwards from the end of the list but don’t know how to do it in c# with game object.transform
Any ideas?

Manual reverse iteration is possible using the GetChild() and childCount variables:

for (int i=old_parent.childCount-1; i >= 0; --i) {
    Transform child = old_parent.GetChild(i);
    Debug.Log("moving object: " + child.name);
    child.SetParent(new_parent.transform, false);
}

Additionally, this method performs no allocations, which is a nice bonus!

A simple while loop like this does the trick too:

Transform newParent = someTransform;
Transform oldParent = someTransform;
while (oldParent.childCount > 0) {
	oldParent.GetChild(oldParent.childCount - 1).SetParent(newParent, false);
}

This iterates from the last/highest entry to the first/lowest entry.

Note that this puts all children in reversed hierarchy order into the new parent, so the first child becomes the last child.