Delete all child nodes of node:
Error method:
int childCount = Node.transform.childCount;
for (int i=0; i<childcount; i++) {
Gameobject Child=node.transform.getchild (i). Gameobject;
Destroy (child);
}
The above method is wrong because destroy in the next frame, and in this frame each child also exists, for example, after the above code output Node.transform.childCount will find the result is not 0. So the following logic is dependent on whether or not the child has been deleted immediately (many times there will be dependencies, such as creating a child with the same name after deleting the child and using Findchild to get and modify it, then you will not be able to determine if the deleted or the newly created one has been modified). Can cause strange and strange logic errors.
Correct Method 1:
list<gameobject> childlist = new list<gameobject> ();
int childCount = Node.transform.childCount;
for (int i=0; i<childcount; i++) {
Gameobject Child=node.transform.getchild (i). Gameobject;
Childlist.add (child);
}
for (int i=0; i<childcount; i++) {
Childlist[i].transform.parent=null;
Destroy (Childlist[i]);
}
(Node.transform.childCount = = 0). Mustbetrue ();
Correct Method 2:
list<gameobject> childlist = new list<gameobject> ();
int childCount = Node.transform.childCount;
for (int i=0; i<childcount; i++) {
Gameobject Child=node.transform.getchild (i). Gameobject;
Childlist.add (child);
}
for (int i=0; i<childcount; i++) {
Destroyimmediate (Childlist[i]);
}
Since unity officials strongly deprecated the use of destroyimmediate, it is best to use Method 1.
Unity, Destroy all children