Group Group Group Group Group Group Group Group Group

raywenderlich.com Forums

Object Pooling in Unity

In this tutorial, you'll learn how to create your own object pooler in Unity in a fun 2D shooter.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/847-object-pooling-in-unity

@mplaczek - thanks for the great tutorial. I’ve watched the Unity tutorial on object pooling and also did another from Catlike Coding, and each had their own way of approaching object pooling, which was great. Overall, I liked your approach the best so far.

One small addition I made to the ObjectPooler (an idea from the Catlike Coding tutorial) was to add the pooled objects to a parent object so they don’t fill up the object hierarchy while you’re debugging. I made it so there’s always a root parent object for all pooled objects, but also each ObjectPoolItem can have a pool name that gets assigned to the parent pool to further sub-divide them if you like. My code is below if anyone is interested. Thanks again for this tutorial, always looking to learn new and better techniques.

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class ObjectPoolItem
{
    public GameObject objectToPool;
    public string poolName;
    public int amountToPool;
    public bool shouldExpand = true;
}

public class ObjectPooler : MonoBehaviour
{
    public const string DefaultRootObjectPoolName = "Pooled Objects";

    public static ObjectPooler Instance;
    public string rootPoolName = DefaultRootObjectPoolName;
    public List<GameObject> pooledObjects;
    public List<ObjectPoolItem> itemsToPool;

    void Awake()
    {
        Instance = this;
    }

    private void Start()
    {
        if (string.IsNullOrEmpty(rootPoolName))
            rootPoolName = DefaultRootObjectPoolName;

        GetParentPoolObject(rootPoolName);

        pooledObjects = new List<GameObject>();
        foreach (var item in itemsToPool)
        {
            for (int i = 0; i < item.amountToPool; i++)
            {
                CreatePooledObject(item);
            }
        }
    }

    private GameObject GetParentPoolObject(string objectPoolName)
    {
        // Use the root object pool name if no name was specified
        if (string.IsNullOrEmpty(objectPoolName))
            objectPoolName = rootPoolName;

        GameObject parentObject = GameObject.Find(objectPoolName);

        // Create the parent object if necessary
        if (parentObject == null)
        {
            parentObject = new GameObject();
            parentObject.name = objectPoolName;

            // Add sub pools to the root object pool if necessary
            if (objectPoolName != rootPoolName)
                parentObject.transform.parent = GameObject.Find(rootPoolName).transform;
        }

        return parentObject;
    }

    public GameObject GetPooledObject(string tag)
    {
        for (int i = 0; i < pooledObjects.Count; i++)
        {
            if (!pooledObjects[i].activeInHierarchy && pooledObjects[i].CompareTag(tag))
                return pooledObjects[i];
        }

        foreach (var item in itemsToPool)
        {
            if (item.objectToPool.CompareTag(tag))
            {
                if (item.shouldExpand)
                {
                    return CreatePooledObject(item);
                }
            }
        }

        return null;
    }

    private GameObject CreatePooledObject(ObjectPoolItem item)
    {
        GameObject obj = Instantiate<GameObject>(item.objectToPool);

        // Get the parent for this pooled object and assign the new object to it
        var parentPoolObject = GetParentPoolObject(item.poolName);
        obj.transform.parent = parentPoolObject.transform;

        obj.SetActive(false);
        pooledObjects.Add(obj);
        return obj;
    }
}
1 Like

Hi!
Thank you for your kind words… That was a very nice way to start the new year!
And thank you for posting your code, I too am always looking to learn new and better techniques, and that does indeed seem like a great way to keep things organised while testing your new game, never a bad thing at all :]

Hello, Great tutorial.

I’m beginner in unity and you helped me a lot.

Thanks and I’m already sign in and going to see more tutorials.

So I created a gist of the ObjectPooler in the way it was shown in the tutorial, if anyone needs it, I’m sharing the link below:

This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]