Golf2D/Assets/Scripts/ObjectPool.cs
2023-10-18 22:44:51 +05:30

62 lines
1.8 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
public static ObjectPool instance;
public static Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>();
void Awake(){
pool = new Dictionary<string, List<GameObject>>();
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<GameObject>());
}
pool[objName].Add(obj);
obj.SetActive(false);
// Debug.Log($"Adding {objName} back to pool, " + pool[objName].Count);
}
}