- Home /
[best practices] Safely Destroy entries while iterating over them?
Just happened upon this in the docs:
Also note that you should never iterate through arrays and destroy the elements you are iterating over. This will cause serious problems (as a general programming practice, not just in Unity).
I do this all the time with inverted loops and never have any issues, so I wondered, what is the truth behind this cautionary statement? Is this actually a dangerous thing to do for some reason I've yet to encounter? Big thanks,
for (int = collection.Count-1; i>=0; i--) Destroy( collection[i] );
edit to include docs link: http://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html
Got a link to the statement?
Elements or element contents?
I think this refers to the mechanic of DestroyImmediate rather than destroy.
But, I guess it leads to bad indexing. If an element is destroyed during a loop perhaps it is not consolidated till the end of the frame leaving discontinuity.
In the example of a List, where the List is automatically resized you could end up skipping elements, perhaps.
I'm sure you're quite right, which is why a reverse loop is necessary to resolve indexing kerfuffles. It never created a problem for me before, so that statement seemed funny to me. Thanks,
Answer by smoggach · Feb 03, 2015 at 03:00 PM
It's only dangerous if you do it wrong, which is very easy to do.
DestroyImmediate is meant for use in the Editor. Destroy uses garbage collection which is why you don't have problems destroying things while iterating over them (they still live for a frame or two).
I wondered whether this might be specific to DestroyImmediate and Editor scripting. It wasn't worded as such, so I was confused by the statement. Appreciate the feedback,
Yeah, the wording suggests Destroy in general.
I've been told use of DestroyImmediate is bad but I needed it in a build of $$anonymous$$e and it was fine. Its just dangerous.
Your answer
Follow this Question
Related Questions
Best practice for object communication 3 Answers
Which to use Arrays, Collections, Lists and Generics 0 Answers
Best Practices for exception handling Resource.Load 1 Answer
Propogate upgrade to different entities (Wepon upgrade System) 1 Answer
What is the best practice in handling scenes with 100+ rigidbodies and collisions on iOS? 1 Answer