- Home /
Clear whole list
Hi! Is there a possibility to clear a whole list (the index entries and the objects) with just a simple command, so that the list will be empty and the size of the elements will be 0 again, and the objects distroyed? Something like Clear() or RemoveAll()?
I have this code so far, but isn't there a simpler way to do it that takes less time?
using System.Linq;
using System.Collections.Generic;
public List <GameObject> WP;
WP = GameObject.FindGameObjectsWithTag("waypoints").OrderBy( go => go.name ).ToList();
foreach (GameObject goWp in WP)
{
Destroy (goWp);
}
for (var i = 0; i < WP.Count; i++)
{
WP.RemoveAt(i);
}
Answer by DESTRUKTORR · Sep 03, 2013 at 05:34 PM
The list clear method simply loops through and clears out all the entries for the list, same as this does. Unless your list is massive in size, clearing out basic objects from it shouldn't take that much time.
On another note, why is it you need to destroy the game objects? Destroying game objects is quite costly, and is often suggested against.
I usually just make a linked list "buffer" of game objects with the components I need them to have and enable/disable them, dynamically by simply pushing and popping them off, like a stack, disabling the game object when it's pushed to the stack, and re-enabling them when they're popped off.
While various methods will often make it seem as though collections can be cleared/created with one command, the methods themselves will still use looping or recursion to execute the exact same thing, as it's impossible to do it any other way, really.
$$anonymous$$y actually problem was, that I could not use the List any longer. So I finally could solve the problem simply by Clear() the list and then - if used - just say mayList = new List . Thanks anyway!
Talk about going above and beyond when answering a question.
Your answer
![](https://koobas.hobune.stream/wayback/20220613113521im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can't remove/replace/clear list items 0 Answers
A node in a childnode? 1 Answer
Removing from a list 1 Answer
Remove and resize List 1 Answer
How do I remove a specific item from a list?,How would I remove a specific item in a list? 2 Answers