using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectsPool : MonoBehaviour { public static ObjectsPool instance; public int pooledItems; private void Awake() { instance = this; } public Dictionary> pooled = new Dictionary>(); public Dictionary> borrowed = new Dictionary>(); public GameObject Spawn(GameObject go, Vector3 position, Quaternion rotation, float destructionTimer = 0, bool effect = false) { //CheckPool(); GameObject inst = BorrowItem(go.name); if(inst == null) { inst = Instantiate(go,transform); } // GameObject inst = (pooled.ContainsKey(go.name)) ? BorrowItem(go.name) : Instantiate(go,transform); inst.name = go.name; inst.transform.position = position; inst.transform.rotation = rotation; if(borrowed.ContainsKey(go.name)) { borrowed[go.name].Add(inst); }else { borrowed.Add(go.name, new List() { inst }); } if (destructionTimer > 0) { StartCoroutine(SelfDestruct(inst,destructionTimer)); } if(effect) { ParticleSystem[] particleSystems =GetComponentsInChildren(); AudioSource[] audioSources = GetComponentsInChildren(); foreach(ParticleSystem particle in particleSystems) { particle.Play(); } foreach(AudioSource audioSource in audioSources) { audioSource.Play(); } } return inst; } IEnumerator SelfDestruct(GameObject go,float timer) { yield return new WaitForSeconds(timer); ReturnItem(go); } public GameObject BorrowItem(string name) { //CheckPool(); if (!pooled.ContainsKey(name)) { return null; } if (pooled[name].Count == 0) { return null; } GameObject item = pooled[name][0]; if(borrowed.ContainsKey(name)) { borrowed[name].Add(item); }else { borrowed.Add(name, new List() { item }); } item.SetActive(true); pooled[name].RemoveAt(0); // Debug.Log($"{name}: {pooled[name].Count}"); return item; } public void ReturnItem(GameObject item) { // CheckPool(); if (!borrowed.ContainsKey(item.name)) { Debug.LogError($"{item.name} was not borrowed to return!"); } else { borrowed[item.name].Remove(item); } if(pooled.ContainsKey(item.name)) { if (pooled[item.name].Contains(item)) { Debug.LogError("Already returned!"); } else { pooled[item.name].Add(item); } }else { pooled.Add(item.name, new List() { item }); } item.SetActive(false); } }