Unity, Destroy all children

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.