using UnityEngine; using System.Collections.Generic; /* This PoolingManager class aims to manage and recycle instancied prefabs. When in need of a new instance, ask this PoolingManager to provide it. It will check if a disabled instance of your specified prefab is avalaible and if not, it will create a new instance. Just make sure that instead of destroying prefabs, they are disabled once they have achieved their purpose. */ public class PoolingManager : MonoBehaviour { static PoolingManager instance; public static PoolingManager Instance { get { if (instance == null) { instance = FindObjectOfType(); } return instance; } } // A dictionnary is used to keep references of all instancied objects in the scene. // The key is the name of a prefab and is associated with a list of all created instances of that prefab Dictionary> _instanciedObjects; void Start() { _instanciedObjects = new Dictionary>(); } public GameObject Provide(GameObject pPrefab) { GameObject result = null; if (_instanciedObjects.ContainsKey(pPrefab.name)) { List existingObjects = _instanciedObjects[pPrefab.name]; // Check if there's an available(disabled) object to reuse before creating a new one : foreach(GameObject obj in existingObjects) { if(obj.gameObject.activeInHierarchy == false) { result = obj; break; } } // No available object so create one : if(result == null) { result = CeateNewObject(pPrefab); existingObjects.Add(result); } } else { // No object of this prefab was instancied before so create a new object and a new list to store the future objects of its kind result = CeateNewObject(pPrefab); List newList = new List(); newList.Add(result); _instanciedObjects.Add(pPrefab.name, newList); } result.gameObject.SetActive(true); return result; } GameObject CeateNewObject(GameObject pPrefab) { var newObject = Instantiate(pPrefab); return newObject; } // Useful to call when the game has to be reset, for example. public void DeactivateAllObjects() { foreach (KeyValuePair> keyValue in _instanciedObjects) { List list = keyValue.Value; foreach (GameObject obj in list) { obj.gameObject.SetActive(false); } } } }