Object Pooling – Unity Asset Hub

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);
    }
}
.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock