Skip to content

Instantly share code, notes, and snippets.

@stipebosnjak
Created November 2, 2018 02:16
Show Gist options
  • Save stipebosnjak/8f35b90cfb176af3aa51188e646401cd to your computer and use it in GitHub Desktop.
Save stipebosnjak/8f35b90cfb176af3aa51188e646401cd to your computer and use it in GitHub Desktop.
Unity3D - Expandable Object Pooler
using System.Collections.Generic;
using UnityEngine;
namespace Utils
{
[System.Serializable]
public class ObjectPoolItem
{
public GameObject objectToPool;
public int amountToPool;
public bool shouldExpand;
}
public class ObjectPooler : MonoBehaviour
{
public static ObjectPooler Instance;
public List<ObjectPoolItem> itemsToPool;
public List<GameObject> pooledObjects;
public GameObject ParentObject;
public void Awake()
{
Instance = this;
}
public void Start()
{
pooledObjects = new List<GameObject>();
foreach (ObjectPoolItem item in itemsToPool)
{
for (int i = 0; i < item.amountToPool; i++)
{
var obj = Instantiate(item.objectToPool, ParentObject.transform);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
}
public GameObject GetPooledObject(string tag)
{
foreach (var t in pooledObjects)
{
if (!t.activeInHierarchy && t.CompareTag(tag))
{
return t;
}
}
foreach (ObjectPoolItem item in itemsToPool)
{
if (item.objectToPool.CompareTag(tag))
{
if (item.shouldExpand)
{
var obj = Instantiate(item.objectToPool, ParentObject.transform);
obj.SetActive(false);
pooledObjects.Add(obj);
return obj;
}
}
}
Debug.LogWarning("Returning null for tag: " + tag);
return null;
}
}
}
@stipebosnjak
Copy link
Author

Not mine, creds to the Creator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment