Skip to content

Instantly share code, notes, and snippets.

@alegueleres
Last active September 18, 2018 07:37
Show Gist options
  • Save alegueleres/6b05835f958215763f4244e1f53e2ce9 to your computer and use it in GitHub Desktop.
Save alegueleres/6b05835f958215763f4244e1f53e2ce9 to your computer and use it in GitHub Desktop.
Object Pooler used in Unity to instantiate objects in the level load of game, and use this instances, instead creating and destroying objects. The reason is to save CPU processment. Used the tutorial: https://www.raywenderlich.com/136091/object-pooling-unity. You can verify how to use this object pooler, it is a very cool approach.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour {
public static ObjectPooler SharedInstance;
public List<ObjectPoolItem> itemsToPool;
public List<GameObject> pooledObjects;
void Awake()
{
SharedInstance = this;
}
// Use this for initialization
void Start () {
pooledObjects = new List<GameObject>();
foreach (ObjectPoolItem item in itemsToPool)
{
for (int i = 0; i < item.amountToPool; i++)
{
GameObject obj = (GameObject)Instantiate(item.objectToPool);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
}
public GameObject GetPooledObject(string tag)
{
for (int i = 0; i < pooledObjects.Count; i++)
{
if (!pooledObjects[i].activeInHierarchy && pooledObjects[i].tag == tag)
{
return pooledObjects[i];
}
}
foreach (ObjectPoolItem item in itemsToPool)
{
if (item.objectToPool.tag == tag)
{
if (item.shouldExpand)
{
GameObject obj = (GameObject)Instantiate(item.objectToPool);
obj.SetActive(false);
pooledObjects.Add(obj);
return obj;
}
}
}
return null;
}
[System.Serializable]
public class ObjectPoolItem
{
public int amountToPool;
public GameObject objectToPool;
public bool shouldExpand;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment