using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPool : MonoBehaviour { public static ObjectPool instance; public static Dictionary> pool = new Dictionary>(); void Awake(){ pool = new Dictionary>(); instance= this; } public static GameObject Spawn(GameObject obj, Vector3 position){ if(pool.ContainsKey(obj.name)){ // Debug.Log($"Has key : {pool[obj.name].Count}"); //use from pool if(pool[obj.name].Count <=0){ GameObject go = Instantiate(obj, position, Quaternion.identity); return go; }else{ GameObject chosen = pool[obj.name][0].gameObject; chosen.gameObject.SetActive(true); chosen.transform.position = position; pool[obj.name].RemoveAt(0); // Debug.Log("Reusing"); return chosen; } }else{ GameObject go = Instantiate(obj, position, Quaternion.identity); return go; } } public static void Despawn(GameObject obj){ string objName = obj.name.Replace("(Clone)",""); if(!pool.ContainsKey(objName)){ pool.Add(objName, new List()); } pool[objName].Add(obj); obj.SetActive(false); // Debug.Log($"Adding {objName} back to pool, " + pool[objName].Count); } }