Example Patterns‎ > ‎

Using SpawnPool as a List

SpawnPools can also be iterated through as a List of Transforms where only spawned (active) instances are available in the list.

In the following example, all active instances of a SpawnPool "Enemies" are despawned:


// Make sure you have this at the top of your script to be able use the 
//   generic list
using System.Collections.Generic;
...

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

// Make a copy of the list of enemies in case it changes during the loop
List<Transform> enemiesCopy = new List<Transform>(enemies);

// Print the number of spawned instances before
Debug.Log("Starting count: " + enemies.Count);

// Iterate over the copy but despawn the instances from the actual pool
foreach (Transform enemy in enemiesCopy)
{
enemies.Despawn(enemy);
Debug
.Log(
"Count: " + enemies.Count);  // Will go down each iteration.
}


Here is another way to iterate until all are despawned. This is from the example files which you can download from the documentation home page. This uses a co-routine which will not only despawn everything, but will do it one at a time ever X seconds (You would still need to start the co-routine as shown in the Unity Documentation). 

This version has the following points of interest:
  • Good: Has the advantage of not needing a copy of the list. This is great if you think the list could be changed by other scripts in your game while this loop is running!

  • Bad: Really doesn't offer any more performance than the example above and adds the possibility of getting it wrong and ending up in an infinite loop.

    /// <summary>
    /// Despawn an instance every X seconds
    /// </summary>
    private IEnumerator Despawner()
    {
        // Create a short reference to the pool
        SpawnPool pool PoolManager.Pools["Enemies"];
        while (pool.Count() > 0)
        {
            // Despawn the last instance (like dequeue in a queue because 
            //   Despawn() will also remove the item from the list, so the list
            //   is being changed in-place.)
            Transform instance = pool[pool.Count - 1];
            this.pool.Despawn(instance);  // Internal count--

            yield return new WaitForSeconds(1);  // Runs every 1 second
        }
    }



For more regarding using a SpawnPool as a list, continue on to "Copy List of Spawns"...