Children detach not working

Hi,

So I have this problem - i have a function that searches child objects by name with foreach loop and simply makes their transform.parent null, after it is done I deactivate the function with boolean, yet the problem is, doesn’t matter how many children the object has, it will always detach only a half of them and then stop.

Here’s the code, please help me if you know why it’s not working.

Thanks in advance!

void DetachChildren()

{
	if(finished==false)
	{
		foreach(Transform child in transform)
		{
			if(child.gameObject.name=="ChildName")
			{
				child.transform.parent=null;
			}
		}
		finished=true;
	}
}

Assuming all of your game objects are immediate children, my educated guess is that the setting of null is modifying the list you are trying to iterate through it. Try something like this instead:

    Transform[] trans = GetComponentsInChildren<Transform>();

    foreach (t in trans) {
        if (t.parent == transform) {
            t.parent = null;
        }
    }

This will break away the immediate children. If you want to break all child bonds, use:

      if (t != transform)

Note that the list will include the transform of the game object at the root.