- Home /
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;
}
}
Answer by robertbu · Oct 01, 2014 at 12:22 AM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613164124im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
transform.DetachChildren() is deactivating my children's scripts after detaching from the parent 1 Answer
Add force to child 1 Answer
How to have child object remain after parent is destroyed? 1 Answer
Detach children on button press 1 Answer
How to sync children of a gameObject using Photon? 0 Answers