Pool Manager

When I started to understand the importance of object pooling in Unity, I had a hard time finding an implementation that fit my needs. I love the asset store and frequently indulge in purchases that may someday be useful on any one of a dozen ideas I have at the back of my mind – some gamers have a Steam backlog, I have an Asset Store backlog! But in this case, I really just wanted something simple and free. I didn’t need my pool manager to have a ton of fancy features, nor did I want to take on a lot of overhead altering the objects I wanted to pool.

So, I went with a homegrown solution. My implementation simply serves up an instance of the desired prefab: either a reactivated instance from the pool or, if there are no available pooled objects, a newly-instantiated one. This pool manager only manages one prefab each, so it would need retooling to be applicable on a game with lots of different pooled objects. But in situations where just one type shows up frequently and the size of the pool doesn’t increase dramatically over time (tiles in a puzzle game, asteroids in Voyager), it works grand:

// --------------------------------
// <copyright file="UnityPoolManager.cs" company="Rumor Games">
//     Copyright (C) Rumor Games, LLC.  All rights reserved.
// </copyright>
// --------------------------------

using System.Collections.Generic;
using System.Globalization;
using UnityEngine;

/// <summary>
/// UnityPoolManager class.
/// </summary>
public class UnityPoolManager : MonoBehaviour
{
    /// <summary>
    /// Template object to copy.
    /// </summary>
    public GameObject prefab;

    /// <summary>
    /// Whether to reparent the object on pooling.
    /// </summary>
    public bool reparent = true;

    /// <summary>
    /// If reparenting objects, the Transform to parent active objects under.
    /// </summary>
    [HideUnless("reparent")]
    public Transform activeParent;

    /// <summary>
    /// If reparenting objects, the Transform to parent inactive objects under.
    /// </summary>
    [HideUnless("reparent")]
    public Transform inactiveParent;

    /// <summary>
    /// Data structure backing pool.
    /// </summary>
    private Stack<GameObject> pool;

    /// <summary>
    /// Number of instances created of each object type.
    /// </summary>
    private IDictionary<string, int> instanceCount;

    /// <summary>
    /// Initialize script state.
    /// </summary>
    internal virtual void Awake()
    {
        this.pool = new Stack<GameObject>();
        this.instanceCount = new Dictionary<string, int>();
        if (this.inactiveParent == null)
        {
            this.inactiveParent = this.transform;
        }
    }

    /// <summary>
    /// Get an object from the pool if available, otherwise creates a new instance.
    /// </summary>
    /// <returns>An object from the pool.</returns>
    public GameObject Get()
    {
        GameObject poolObject;

        // try to get from pool first
        if (this.pool.Count > 0)
        {
            poolObject = this.pool.Pop();
        }
        else
        {
            if (!this.instanceCount.ContainsKey(this.prefab.name))
            {
                this.instanceCount.Add(this.prefab.name, 0);
            }

            // if pool is empty, create a new instance
            poolObject = Instantiate(this.prefab);
            poolObject.name = string.Format(CultureInfo.InvariantCulture, "{0}({1})", this.prefab.name, this.instanceCount[this.prefab.name]);
            poolObject.transform.SetParent(this.inactiveParent, false);

            this.instanceCount[this.prefab.name]++;
        }

        // reparent if desired
        if (this.reparent)
        {
            poolObject.transform.SetParent(this.activeParent, false);
        }

        // activate object
        poolObject.SetActive(true);

        return poolObject;
    }

    /// <summary>
    /// Release an object back to the pool.
    /// </summary>
    /// <param name="poolObject">Object to release.</param>
    public void Release(GameObject poolObject)
    {
        // deactivate object
        poolObject.SetActive(false);

        // reparent if desired
        if (this.reparent)
        {
            poolObject.transform.SetParent(this.inactiveParent, false);
        }
        
        // return to pool
        this.pool.Push(poolObject);
    }
}

Since it doesn’t have any deep hooks into the pooled objects and instead simply activates and deactivates them, it’s up to me to remember to implement appropriate setup and hibernation logic in OnEnable and OnDisable. It’s a tradeoff – less overhead, more implementation complexity. Still, I can (and do) extend this pool manager with specialized implementations that handle the busy work.

While the script as written only allows for one prefab per pool, it’d be easy enough to extend it with a templatized get and release method (and modified backing data structure to match), but this should be suitable for basic needs or anyone looking for a place to start.

Bookmark the permalink.

Comments are closed