using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour
{
[SerializeField] private GameObject objectPrefab;
[SerializeField] private int poolSize = 10;
private Queue<GameObject> objectPool = new Queue<GameObject>();
// Create the object pool on Start
private void Start()
{
for (int i = 0; i < poolSize; i++)
{
GameObject obj = Instantiate(objectPrefab, transform);
obj.SetActive(false);
objectPool.Enqueue(obj);
}
}
// Get an object from the pool
public GameObject GetObject()
{
if (objectPool.Count == 0)
{
// If the pool is empty, create a new object
GameObject obj = Instantiate(objectPrefab, transform);
obj.SetActive(false);
objectPool.Enqueue(obj);
}
// Dequeue an object from the pool and return it
GameObject pooledObject = objectPool.Dequeue();
pooledObject.SetActive(true);
return pooledObject;
}
// Return an object to the pool
public void ReturnObject(GameObject obj)
{
obj.SetActive(false);
objectPool.Enqueue(obj);
}
}
.