95 lines
2.9 KiB
C#
95 lines
2.9 KiB
C#
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<string, List<GameObject>> pooled = new Dictionary<string, List<GameObject>>();
|
|
public Dictionary<string,List<GameObject>> borrowed = new Dictionary<string, List<GameObject>>();
|
|
|
|
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<GameObject>() { inst }); }
|
|
|
|
|
|
if (destructionTimer > 0)
|
|
{
|
|
StartCoroutine(SelfDestruct(inst,destructionTimer));
|
|
}
|
|
|
|
if(effect)
|
|
{
|
|
ParticleSystem[] particleSystems =GetComponentsInChildren<ParticleSystem>();
|
|
AudioSource[] audioSources = GetComponentsInChildren<AudioSource>();
|
|
|
|
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<GameObject>() { 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<GameObject>() { item }); }
|
|
item.SetActive(false);
|
|
}
|
|
}
|