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 pools; public Dictionary> poolDictionary; void Start() { poolDictionary = new Dictionary>(); foreach (Pool pool in pools) { Queue objectPool = new(); for (int i = 0; i < pool.size; i++) { GameObject obj = Instantiate(pool.prefab); obj.SetActive(false); objectPool.Enqueue(obj); } poolDictionary.Add(pool.tag, objectPool); } } public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation) { if (!poolDictionary.ContainsKey(tag)) { Debug.Log("Pool does not contain tag: " + tag); return null; } GameObject objectToSpawn = poolDictionary[tag].Dequeue(); IPooledObject pooledObject = objectToSpawn.GetComponent(); objectToSpawn.transform.SetPositionAndRotation(position, rotation); pooledObject?.OnObjectSpawn(); // The OnObjectSpawn method determines how the object behaves after spawning objectToSpawn.SetActive(true); poolDictionary[tag].Enqueue(objectToSpawn); // Add the object back to the queue return objectToSpawn; } }