using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; 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, int ttl = 0){ 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"); if (ttl > 0) { Deactivate(chosen, ttl); } return chosen; } }else{ GameObject go = Instantiate(obj, position, Quaternion.identity); if(ttl > 0) { Deactivate(go, ttl);} return go; } } async static void Deactivate(GameObject go, int ttl) { await Task.Delay(ttl); Despawn(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); } }