UPF/Assets/Game/Scripts/EffectPool.cs
2023-02-24 22:14:55 +05:30

82 lines
2.6 KiB
C#
Executable File

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EffectPool : MonoBehaviour
{
[SerializeField]private Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>();
[SerializeField]private Dictionary<string, List<GameObject>> active= new Dictionary<string, List<GameObject>>();
[SerializeField]private Transform EffectsParent;
public static EffectPool instance {get; private set;}
void Awake(){
instance = this;
pool = new Dictionary<string, List<GameObject>>();
active= new Dictionary<string, List<GameObject>>();
}
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<GameObject>());
}
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<GameObject>());
}
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<ParticleSystem>();
foreach(ParticleSystem particle in particles){
particle.Play();
}
AudioSource[] audios = item.GetComponentsInChildren<AudioSource>();
foreach(AudioSource audio in audios){
audio.Play();
}
return item;
}
}