Created
November 2, 2018 02:16
-
-
Save stipebosnjak/8f35b90cfb176af3aa51188e646401cd to your computer and use it in GitHub Desktop.
Unity3D - Expandable Object Pooler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not mine, creds to the Creator.