My Improved Unity Object Pool Class

Nice, little updates to code are… well, nice! I’ve been using a home-grown object pooler in Unity, and you may recall I wrote about that here.  It’s a very simple, yet effective way of creating a pool of objects.

Originally, I used List<GameObject> and looped through the list to find an unused game object. Thinking about it a bit, I realized I could use a queue instead.  Here’s the updated code:

using UnityEngine;
using System.Collections.Generic;

public class Pooler : MonoBehaviour {

    public GameObject pooledObject;     // object to pool, drag into Inspector
    public int pooledAmount;            // number of objects, drag into Inspector
    public string objectName;           // name of object, enter into Inspector

    private Queue<GameObject> pooledObjects;

    /// <summary>
    /// Inits the object pool.  Renames the pool objects to the objectName
    /// </summary>
    void Awake() {
        pooledObjects = new Queue<GameObject>();

        for (int i = 0; i < pooledAmount; i++) {
            GameObject obj = (GameObject) Instantiate(pooledObject, Vector3.zero, Quaternion.identity);
            if (objectName != "") obj.name = objectName;
            obj.SetActive(false);
            obj.transform.SetParent(transform, false);
            pooledObjects.Enqueue(obj);
        }
    }

    /// <summary>
    /// Gets the pooled object.
    /// </summary>
    /// <returns>The pooled object or null if all objects are used.</returns>
    public GameObject GetPooledObject() {
        if (pooledObjects.Count == 0) return null;
        return pooledObjects.Dequeue();
    }

    public void ReturnToPool(GameObject obj) {
        obj.SetActive(false);
        pooledObjects.Enqueue(obj);
    }
}

Using Queue<GameObject>, there is no need to loop through a list.  The Dequeue statement at line 33 will remove the first item from the queue and return it. I added the ReturnToPool method, so I can disable the object and add it back to the queue when I am done with it.

This object pooler is a basic and easy to use. Feel free to use or modify it if it works for you.

To use it, place this script on an empty game object, drag in a prefab, choose how many objects you want to create, and name it something.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: