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"]; // Make a copy while getting a new list var enemiesCopy = new List<Transform>(enemies); // 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) |
Example Patterns >