Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Optimization and Publishing

Object Pooling and Memory in Unity

Stop spikes from Instantiate and Destroy with object pooling in Unity - ObjectPool<T>, bullet pools, addressables and asset loading, texture memory - with runnable pool stand-ins.

Every shot fired in a shooter normally does Instantiate(bullet), and a second later Destroy(bullet). Creating and destroying game objects is one of the most expensive things you can do per frame: it allocates memory, runs Awake and OnEnable, registers physics and rendering data, and later triggers garbage collection. Fire thirty bullets a second and the frame rate stutters.

Object pooling fixes this by creating objects once, keeping them inactive, and reusing them. This lesson builds a pool from scratch, shows Unity's built-in ObjectPool<T>, and then widens the view to memory: textures, asset loading and Addressables.

The idea

A pool has a stack of ready objects. Get pops one (or creates one if the stack is empty), activates it and resets it. Release deactivates it and pushes it back. No allocation happens after the pool has warmed up.

flowchart LR
  P["Pool<br/>inactive objects"] -->|"Get()"| A["Active in scene"]
  A -->|"Release()"| P
  P -->|"empty?"| N["Create new object"]
  N --> A

Objects circulate between the pool and the scene instead of being created and destroyed.

The stand-in below implements a generic pool with a maximum size and counts how many objects are really constructed, which is what you want to minimize.

C# Stand-in: a generic object pool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Only two or three bullets are ever created even though twenty are fired. In Unity the "create" step is Instantiate and the "reset" step turns the object off or on.

Unity's ObjectPool

Unity 2021 and later includes UnityEngine.Pool.ObjectPool<T> so you do not need to write your own. You give it four callbacks:

C#
using UnityEngine;
using UnityEngine.Pool;

public class BulletSpawner : MonoBehaviour
{
    [SerializeField] Bullet prefab;
    ObjectPool<Bullet> pool;

    void Awake()
    {
        pool = new ObjectPool<Bullet>(
            createFunc:      () => { var b = Instantiate(prefab); b.Init(pool); return b; },
            actionOnGet:     b => b.gameObject.SetActive(true),
            actionOnRelease: b => b.gameObject.SetActive(false),
            actionOnDestroy: b => Destroy(b.gameObject),
            collectionCheck: true,   // editor-only check against double release
            defaultCapacity: 20,
            maxSize:         100);
    }

    public void Fire(Vector3 position, Vector3 direction)
    {
        Bullet b = pool.Get();
        b.transform.SetPositionAndRotation(position, Quaternion.LookRotation(direction));
        b.Launch(direction * 30f);
    }
}

public class Bullet : MonoBehaviour
{
    ObjectPool<Bullet> owner;
    Rigidbody rb;
    public void Init(ObjectPool<Bullet> pool) { owner = pool; rb = GetComponent<Rigidbody>(); }

    public void Launch(Vector3 velocity)
    {
        rb.linearVelocity = velocity;          // Unity 6: linearVelocity (velocity in older versions)
        CancelInvoke();
        Invoke(nameof(Despawn), 2f);
    }

    void Despawn() => owner.Release(this);
}

Related types: ListPool<T>, HashSetPool<T> and DictionaryPool<K,V> give temporary collections without allocation (using (ListPool<Enemy>.Get(out var list)) { ... }).

The pooling checklist

  • Reset all state on Get or Release: velocity, health, trail renderers (Clear()), particle systems, timers, parent and scale. Forgetting to reset is the number one pooling bug, and it produces "ghost" behavior from the previous life.
  • Pre-warm the pool in a loading screen by creating the expected number of objects, so no hitch happens mid-game.
  • Cap the size and decide what happens when the cap is reached (reuse the oldest or refuse).
  • Cancel coroutines and Invokes on release.
  • Do not pool everything: things created rarely, or once per level, do not need it. Pool bullets, particles, floating damage numbers, enemies in waves and audio emitters.
C# Stand-in: the stale-state bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Memory in Unity

Pooling is a micro-fix. The bigger memory costs in a game are assets:

  • Textures are usually the largest. A 2048x2048 RGBA texture is 16 MB uncompressed; with ASTC compression it is a fraction. Reduce Max Size, turn off Read/Write, and disable mipmaps on UI textures.
  • Meshes and animation with Read/Write on keep a CPU copy as well as the GPU one.
  • Audio long clips should stream; short ones can load into memory (see Audio sources and the mixer).
  • Scenes hold everything they reference. Loading a new scene unloads the old one, but assets referenced by a persistent singleton stay.

Two tools control when assets load: Resources folders (everything in them goes into the build and cannot be unloaded cleanly; avoid) and Addressables, a package that loads assets by key asynchronously, from the build or a remote server, and lets you release them when you are done:

C#
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public class LevelLoader : MonoBehaviour
{
    [SerializeField] AssetReferenceGameObject bossPrefab;
    AsyncOperationHandle<GameObject> handle;

    async void SpawnBoss()
    {
        handle = bossPrefab.InstantiateAsync(Vector3.zero, Quaternion.identity);
        await handle.Task;
    }

    void OnDestroy() => Addressables.ReleaseInstance(handle);   // always release what you load
}

Use Resources.UnloadUnusedAssets() after a scene change if memory climbs, and take Memory Profiler snapshots before and after a level to find leaks, such as an event subscription that keeps a destroyed object alive.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is repeated Instantiate and Destroy expensive?

    Creation and destruction cost CPU time and generate garbage that later triggers the GC.
  2. 2. What is the most common bug when reusing pooled objects?

    A reused object still has its previous life's state unless you reset it.
  3. 3. Which Unity type provides a built-in pool?

    ObjectPool<T> has create, get, release and destroy callbacks plus capacity limits.
  4. 4. What should you do with assets loaded through Addressables when finished?

    Each load is reference counted; releasing lets Unity free the memory.

Summary

  • Pooling reuses objects to avoid Instantiate/Destroy cost and garbage; pre-warm and cap the size.
  • Use ObjectPool<T> or your own pool, and always reset state on reuse.
  • Textures and unnecessary CPU copies dominate memory; compress, shrink and stream.
  • Addressables load and release assets on demand; avoid large Resources folders.

Next: Building and Publishing Your Game