ObjectPool.cs

mail@pastecode.io avatar
unknown
csharp
a month ago
2.6 kB
12
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;


/*
    This class acts as Object Pool, so that we can instantiate as many objects as we need, then we do not call Instantiate during
    gameplay. This way, we prevent slow-downs in the game. 

    PoolObjects is optional, but preferred to be called with specified amount. 
    

*/

public abstract class ObjectPool<T>  : Singleton<ObjectPool<T>> where T : MonoBehaviour
{
    [SerializeField] protected T prefab;
    private List<T> pooledObjects;
    private int amount; 
    private bool isReady;

    // Create with n amount of objects.
    public void PoolObjects(int amount = 0)  // like, Player has box thats nothing in it. 
    {
        if(amount<0)
            throw new ArgumentOutOfRangeException("Amount of pool must be non-negative");
        
        this.amount= amount;
    
        // Initialize the list 
        pooledObjects = new List<T>(amount);
        // Instantiate T's for the list 
        GameObject newObject;
        for(int i=0; i < amount; i++)
        {
            newObject = Instantiate(prefab.gameObject, transform);
            newObject.SetActive(false);
            pooledObjects.Add(newObject.GetComponent<T>());
        }

        // give ready flag 
        isReady = true;
    }


    // get an object from the pool
    public T GetPooledObject() 
    {
        // check if ready, if not, then make it ready 
        if (!isReady)
            PoolObjects(1);
        // search through list for something not in use and return it 
        for (int i =0; i != amount; ++i)
            if(!pooledObjects[i].isActiveAndEnabled) // again this active and enabled thing is from MonoBehaviour
                return pooledObjects[i];

        // if we didnt find anything, make a new one 
        GameObject newObject = Instantiate(prefab.gameObject, transform);
        newObject.SetActive(false);
        pooledObjects.Add(newObject.GetComponent<T>());
        ++amount;
        return newObject.GetComponent<T>();
        // 

    }


    public void ReturnObjectToPool(T returningObject)
    {
        // verify 
        if(returningObject == null)
            return;

        // make sure pool is ready, if not make it ready
        if (!isReady)
        {
            PoolObjects();
            pooledObjects.Add(returningObject);
            amount++;
        }

        returningObject.gameObject.SetActive(false);
        // deactive the object 


    }



}
Leave a Comment