using System.Collections; using System.Collections.Generic; using UnityEngine; public class EffectPool : MonoBehaviour { [SerializeField]private Dictionary> pool = new Dictionary>(); [SerializeField]private Dictionary> active= new Dictionary>(); [SerializeField]private Transform EffectsParent; public static EffectPool instance {get; private set;} void Awake(){ instance = this; pool = new Dictionary>(); active= new Dictionary>(); } public static GameObject Spawn(GameObject prefab, Vector3 position){ return instance.m_Spawn(prefab,position); } GameObject m_Spawn(GameObject prefab, Vector3 position, float delay = 2f){ if(pool.ContainsKey(prefab.name)){ if(pool[prefab.name].Count > 0){ //Has in pool GameObject reactivated = Reactivate(prefab.name,pool[prefab.name][0], position); StartCoroutine(AutoDeactivate(prefab.name, reactivated,delay)); return reactivated; } } //Not in pool GameObject newItem = Instantiate(prefab, EffectsParent); newItem.transform.position = position; if(!active.ContainsKey(prefab.name)){ active.Add(prefab.name, new List()); } active[prefab.name].Add(newItem); StartCoroutine(AutoDeactivate(prefab.name, newItem,delay)); return newItem; } IEnumerator AutoDeactivate(string name, GameObject item, float delay){ yield return new WaitForSeconds(delay); m_deactivate(name,item); } void m_deactivate(string name, GameObject item){ active[name].Remove(item); if(!pool.ContainsKey(name)){ pool.Add(name, new List()); } pool[name].Add(item); } GameObject Reactivate(string name,GameObject item, Vector3 position){ if(!pool.ContainsKey(name)){ throw new System.NullReferenceException("Item not available in pool"); } pool[name].Remove(item); active[name].Add(item); item.transform.position= position; ParticleSystem[] particles = item.GetComponentsInChildren(); foreach(ParticleSystem particle in particles){ particle.Play(); } AudioSource[] audios = item.GetComponentsInChildren(); foreach(AudioSource audio in audios){ audio.Play(); } return item; } }