Created
March 30, 2016 00:28
-
-
Save marcelschmidtdev/c7c56f73b003684b2baa8cd57295044b to your computer and use it in GitHub Desktop.
Really simple ObjectPool for Unity
This file contains hidden or 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 UnityEngine; | |
| using System.Collections.Generic; | |
| public class ObjectPool : MonoBehaviour { | |
| private const int MIN_AMOUNT_OF_POOLED_OBJECTS = 5; | |
| private static ObjectPool _instance; | |
| public static ObjectPool Instance { | |
| get{ | |
| if(_instance == null) { | |
| var go = new GameObject("ObjectPool"); | |
| DontDestroyOnLoad(go); | |
| _instance = go.AddComponent<ObjectPool>(); | |
| } | |
| return _instance; | |
| } | |
| } | |
| private Dictionary<GameObject, Stack<GameObject>> pooledObjects = new Dictionary<GameObject, Stack<GameObject>>(); | |
| public void Preload(GameObject go, int amount) { | |
| if(!pooledObjects.ContainsKey(go)) { | |
| pooledObjects.Add(go, new Stack<GameObject>()); | |
| } | |
| for (int i = 0; i < amount; i++) { | |
| var goInstance = GameObject.Instantiate<GameObject>(go); | |
| var poolMember = goInstance.AddComponent<PoolMember>(); | |
| poolMember.OriginalGameObject = go; | |
| goInstance.SetActive(false); | |
| goInstance.transform.SetParent(this.transform); | |
| pooledObjects[go].Push(goInstance); | |
| } | |
| } | |
| public GameObject Instantiate(GameObject go) { | |
| if(pooledObjects.ContainsKey(go) && pooledObjects[go].Count > 0) { | |
| var pooledGo = pooledObjects[go].Pop(); | |
| pooledGo.transform.SetParent(null); | |
| pooledGo.SetActive(true); | |
| return pooledGo; | |
| } | |
| else { | |
| Preload(go, MIN_AMOUNT_OF_POOLED_OBJECTS); | |
| return Instantiate(go); | |
| } | |
| } | |
| public void Destroy(GameObject go) { | |
| var poolMember = go.GetComponent<PoolMember>(); | |
| pooledObjects[poolMember.OriginalGameObject].Push(go); | |
| go.transform.SetParent(this.transform); | |
| go.SetActive(false); | |
| } | |
| } | |
| public class PoolMember : MonoBehaviour { | |
| public GameObject OriginalGameObject {get; set;} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment