Fur-War/Assets/Scripts/ObjectPooling/ObjectPooler.cs
Gerard Gascón 3b4c6e0ec6 init
2025-04-24 17:29:51 +02:00

62 lines
1.7 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour{
[System.Serializable] public class Pool{
public string tag;
public GameObject prefab;
public int size;
}
public List<Pool> pools;
public Dictionary<string, Queue<GameObject>> poolDictionary;
public static ObjectPooler instance;
void Awake(){
instance = this;
poolDictionary = new Dictionary<string, Queue<GameObject>>();
foreach (Pool pool in pools){
Queue<GameObject> objectPool = new Queue<GameObject>();
for (int i = 0; i < pool.size; i++){
GameObject obj = Instantiate(pool.prefab);
obj.SetActive(false);
obj.transform.parent = transform;
objectPool.Enqueue(obj);
}
poolDictionary.Add(pool.tag, objectPool);
}
}
// Start is called before the first frame update
void Start(){
}
public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation){
if (!poolDictionary.ContainsKey(tag)){
Debug.LogWarning("Pool with tag " + tag + " doesn't exist.");
return null;
}
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.SetActive(true);
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if(pooledObj != null){
pooledObj.OnObjectSpawn();
}
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
}