- Home /
How do I destroy all the GameObjects in an array?
Hi, I'd just like to know if there's some quick way of destroying every GameObject in an array of them. I tried Destroy(array), but Unity didn't like it. I could destroy each one individually using a loop or something, but I think there must be an easier way of doing it than that... Very thank you, and merry unitying!
Answer by clunk47 · Feb 21, 2014 at 09:09 PM
You can do a loop in a couple different ways. for or foreach will work.
if(Inventory.Length > 0)
{
foreach(GameObject go in Inventory)
{
Destroy(go);
}
}
//OR
for(int i = 0; i < Inventory.Length; i++)
{
Destroy(Inventory[i].gameObject);
}
you could risk getting the error that your are changing the size of your iteration while iterating this way if I'm not wrong. I thought it was better to iterate backwards in case of deleting elements. (do correct me if I'm wrong)
for(int i = Inventory.Length-1; i >=0; i--)
{
Destroy(Inventory[i].gameObject);
}
you shouldn't have to worry about that in a loop. Destroy only flags the object to be deleted later, it doesn't do it immediately.
According to this it should. I know I had it several times when removing in a forward loop.
Iterating backwards is only a solution if destroying an item from "Inventory" will change the "Inventory" collection by removing that very item that got destroyed, (which is not possible for an array anyway). It has nothing to do with using Destroy or DestroyImmediate. Also, you can still get problems, e.g. if you remove other items in an collection while destroying items from that collection.
Also, better do not get used to "foreach" for now. Although it looks nicer, due to a bug in $$anonymous$$ono, it will always collect some small memory (at least if you target systems that use the $$anonymous$$ono runtime). Best options is the simple for-loop.
This is true for Foreach loop, if you delete elements from the List using Remove method.
First of all, use List ins$$anonymous$$d of array if adding/deleting expected. You forgot to delete elements from the inventory. If you just Destroy gameobjects, Inventory entry will still exist, but it will be null ins$$anonymous$$d of pointing to gameobject. So Inventory.Count still will be greater than zero. You should either Remove/RemoveAt elements or call Clear().
Answer by jimmycrazyskills · Feb 20, 2014 at 07:12 PM
Sorry if this is wrong , but I think you can do this by using a For loop , the code below is in Javascript and uses an array called "Inventory".
for (var i = 0; i < Inventory.Length; i++) {
Destroy(Inventory[i]);
}
Answer by Contato · Apr 02, 2017 at 10:07 AM
Here it is:
while (Inventory.Length > 0) {
Destroy(Inventory[0]);
}
It will cause the endless cycle, because "Destroy only flags the object to be deleted later, it doesn't do it immediately" as fairly mentioned above.