Game Development Reference
In-Depth Information
The following screenshot shows the List class in the Object Inspector:
Viewing the List class in the Object Inspector
The List class supports several methods to remove items either individually
or collectively, and these are intended to be used outside list iterations (loops).
However, there are times when it's convenient, or seems simplest, to remove
items while iterating through a loop, such as when you need to remove each item
after processing it. A classic case is when you need to delete all reference type objects
in the scene, such as enemies, while also removing their entry in the array to avoid
null references. Item removal in a loop, however, can cause problems, because it's
easy for an iterator to lose track of where it is and where it should go within the
array as the total item count changes during the loop. To loop and remove in
one process, you should traverse the array backwards from the end to the start,
as opposed to forwards, as shown in the following code sample 6-2:
//Remove all items from a loop
void RemoveAllItems()
{
//Traverse list backwards
for(int i = Enemies.Count-1; i>=0; i--)
{
//Call function on enemy before removal
Enemies[i].MyFunc();
 
Search WWH ::




Custom Search