Example Patterns‎ > ‎

Copy List of Spawns

It can be necessary to copy a list when you want to iterate through it and make potential changes. For example, if you despawn an instance the SpawnPool list will change because it only contains spawned instances. If you copy the list before editing the SpawnPool, your foreach loop won't break.

For these examples, assume this code comes first so we can keep the code short

// Make a shorter name for the pool so it is easier to type
SpawnPool
enemies =
PoolManager.Pools["Enemies"];

The easiest way to create a copy is to pass the SpawnPool in to the constructor of the new list when it is made, like this (I am using 'var' here because it is obvious what the type is) :

// Make a copy while getting a new list
var
enemiesCopy = new List<Transform>(enemies);

This is also very fast but passes the contents of one list to the end of another list using AddRange(). This is great if you only want to make a single list in memory and recycle it using Clear() rather than making a new one each time.

// Make a copy by adding the entire list to another list using AddRange()
var enemiesCopy = new List<Transform>();
enemiesCopy.AddRange(enemies);

enemiesCopy.Clear();           // Clear the list so it is empty again
enemiesCopy.AddRange(enemies); // Add the entire enemies list again (copy)