liveBook · Manning

Object pool

As explained in High Performance Unity Game Development

A preallocated collection of slots that holds data or objects for reuse.

Suppose a survival game spawns enemies as the player moves and removes them when they are defeated. Instantiating a Unity GameObject for every spawn and destroying it afterward repeatedly allocates memory. Destroy does not make that memory immediately reusable: the garbage collector must run first. Frequent allocation and removal can fragment memory and cause unpredictable slowdowns during play. section 3.3 section 3.3.1

An object pool keeps a bounded set of reusable slots. For a level with a known enemy limit, create an array and instantiate its GameObjects while the level loads. Leave them inactive until needed. Spawning takes an unused object and activates it; removal deactivates it without destroying it. Destroy the pool when the level ends. Gameplay can then spawn and remove enemies without further GameObject allocation. section 3.3.2 section 3.5

Listing 3.5 Functions to allocate and deallocate our enemy pool
GameObject[] m_enemyPool;
 
public void AllocateEnemies(int numEnemies)
{
    m_enemyPool = new GameObject[numEnemies];
    for(int i = 0; i < numEnemies; i++)
    {
        m_enemyPool[i] = Instantiate(enemyPrefab);
        m_enemyPool[i].SetActive(false);
    }
}
 
public void DeallocateEnemies()
{
    for(int i = 0; i < m_enemyPool.Length; i++)
        GameObject.Destroy(m_enemyPool[i]);
    m_enemyPool = null;
}

The allocation functions create inactive enemy GameObjects together and destroy them together at the end of their shared lifetime. section 3.3.2

The pool needs a real capacity limit, not just a guessed array length. Choose the maximum number of simultaneous enemies that the level design permits and the minimum target device can handle. Agree on a rule that enforces it, such as a spawn cap, wave budget or cooldown. If every slot is occupied, do not spawn another enemy. Growing the array at that moment would allocate and copy memory during a heavy workload—the slowdown the pool is meant to avoid. section 3.3.3

A data-oriented version pools more than GameObjects. Fixed-size arrays of positions, directions and velocities also serve as pools; an enemy's index links its data to its visual object. Keep a separate Alive array to record which slots are occupied. Using GameObject.activeSelf for both occupancy and visibility is fragile: hiding enemies while the game is paused must not make their slots appear free. On unpause, restore visibility only for slots marked alive. section 3.3.4

Listing 3.14 Function to spawn an enemy using object pools
public void SpawnEnemy(
    EnemyData enemyData, 
    Vector2 position,
    Vector2 direction,
    float velocity)
{
    for(int i = 0; i < enemyData.NumEnemies; i++)
    {
        if(!enemyData.Alive[i]) #A
        {
            enemyData.Position[i] = position;
            enemyData.Direction[i] = direction;
            enemyData.Velocity[i] = velocity;
            enemyData.Alive[i] = true; #B
            m_enemyPool[i].SetActive(true);
            break;
        }
    }
}

The spawn function fills one free data slot, marks it alive and activates the corresponding GameObject. section 3.3.4

Allocation timing follows the objects' lifetime. If every session uses the same enemy count, the GameObject pool can be initialized once with the board. If levels require different counts or types, allocate for the level and release everything when it ends. Preallocating every GameObject is not always possible: when future enemy types are unknown, keep a fixed maximum pool size, instantiate needed objects as play proceeds, reuse them rather than destroying them, and destroy them together after gameplay. This limits runtime allocation and collection, though it does not eliminate allocation during play. section 5.2.1 section 10.5 section 10.7

How High Performance Unity Game Development covers it

How deep it goes
Works through allocation, spawning, removal, capacity limits and occupancy tracking, then qualifies preallocation when enemy types are unknown.
Examples
Uses Unity enemy-spawning functions, a pause-and-unpause bug, and a pool for randomly selected enemy types.
What it assumes
Assumes familiarity with Unity GameObjects and C# arrays while explaining why repeated instantiation and destruction cause memory-management problems.
What you can do after
Build it from scratch in Unity with a bounded enemy pool, explicit occupancy and a planned full-pool response.
How it connects
Connects data-oriented design and fixed-size arrays with memory fragmentation, garbage collection and GameObject visibility.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.