Problem unparenting c#

Hi everyone,

I have a little weird issue with unparenting with a script. This is my script.

using UnityEngine;
using System.Collections;

public class EjecutarCartas : MonoBehaviour {

	public GameObject hand;

   
public void cancellAll()
	{
		foreach (Transform childTransform in this.transform)
		{
			childTransform.transform.SetParent(hand.transform);
		}
	}
	
	
}

It is attached to the PARENT object and activated by a UI Button.

What brings to my atention is that, when it has only one child works just fine, but if the paren object has two or more childs, what the script does is Unparent all the childs but ONE. So you have to click the button twice.

Am I doing something wrong? Anyone can explain me why this is happening?

Thanks in advance.

I guess you’re looking for this:

    Transform[] childsTransforms = transform.GetComponentsInChildren<Transform>();
    foreach (Transform childTransform in childsTransforms)
    {
        //do your stuff
    }

P.S. Though depending on where you run your code you might actually need this:

    int childCnt = transform.childCount;
    for (int i = 0; i < childCnt; i++)
    {
        Transform childX = transform.GetChild(i);
        //do your stuff
    }