Posted April 04, 2025 by Goutamraj
Added an ObjectPool for MazeCells.
The CellsPool
class is a singleton-based object pooling system designed to manage and reuse maze cell GameObjects efficiently. This avoids frequent instantiation and destruction, improving performance in procedurally generated maze systems.
CellsPool
public static CellsPool instance
: Singleton instance of the pool.
[SerializeField] private Transform pool
: Parent transform to re-parent released objects.
[SerializeField] GameObject cellPrefab
: The prefab used to instantiate new maze cells.
private ObjectPool<GameObject> cellsPool
: The Unity object pool managing the cells.
private List<GameObject> activeCells
: List of currently active cells in the scene.
private void Awake()
Ensures that only one instance of CellsPool
exists using the Singleton pattern.
private void Awake() { if (instance != null && instance != this) { Destroy(gameObject); return; } instance = this; }
public void InitializePool()
Initializes the object pool with callbacks for creating, getting, releasing, and destroying objects.
public void InitializePool() { cellsPool = new ObjectPool<GameObject>( createFunc: () => Instantiate(cellPrefab), actionOnGet: OnGet, actionOnRelease: OnRelease, actionOnDestroy: OnDestroyPooledObject, collectionCheck: true, defaultCapacity: 10, maxSize: 10000 ); }
public GameObject GetCell()
Retrieves an object from the pool.
public GameObject GetCell() { return cellsPool.Get(); }
public void Return(GameObject cellRef)
Returns an object to the pool.
public void Return(GameObject cellRef) { cellsPool.Release(cellRef); }
private void OnGet(GameObject obj)
Activates the cell and tracks it as active.
private void OnGet(GameObject obj) { obj.SetActive(true); activeCells.Add(obj); }
private void OnRelease(GameObject obj)
Deactivates the cell, resets its state, re-parents it, and removes it from active tracking.
private void OnRelease(GameObject obj) { obj.GetComponent<ProceduralMazeGeneation.MazeCell>().ResetMe(); obj.SetActive(false); obj.transform.SetParent(pool); activeCells.Remove(obj); }
private void OnDestroyPooledObject(GameObject obj)
Destroys the GameObject if removed from the pool permanently.
private void OnDestroyPooledObject(GameObject obj) { Destroy(obj); }
public void ReturnAllTakkenObjectsBackToPool()
Returns all currently active objects to the pool.
public void ReturnAllTakkenObjectsBackToPool() { while(activeCells.Count > 0) { Return(activeCells[0]); } }
Efficiently manages maze cell GameObjects.
Uses Unity’s generic object pool API.
Keeps track of active objects.
Ensures smooth reuse of GameObjects to improve performance.
Check out this for code implementation: Pool