Skip to content

Instantly share code, notes, and snippets.

@shane-harper
Created May 19, 2025 13:15
Show Gist options
  • Save shane-harper/4b16e7b773fecf6ba861731ef01e9f2f to your computer and use it in GitHub Desktop.
Save shane-harper/4b16e7b773fecf6ba861731ef01e9f2f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A generic pool manager for managing instances of Unity components.
/// This class allows for efficient reuse of components by maintaining a pool
/// of inactive instances that can be activated and returned as needed.
/// </summary>
/// <typeparam name="T">The type of Unity Component to pool. Must be a class derived from Component.</typeparam>
[Serializable]
public class ComponentPool<T> where T: Component
{
[SerializeField] private Transform _parent;
[SerializeField] private T _prefab;
private readonly Queue<T> _pool = new();
private readonly List<T> _active = new();
public IReadOnlyList<T> Active => _active;
public Transform Parent => _parent;
public ComponentPool()
{
}
public ComponentPool(T prefab, Transform parent) : this()
{
_prefab = prefab;
_parent = parent;
_prefab.gameObject.SetActive(false);
}
public T Get()
{
_prefab.gameObject.SetActive(false);
var instance = _pool.Count <= 0 ? UnityEngine.Object.Instantiate(_prefab, _parent) : _pool.Dequeue();
_active.Add(instance);
return instance;
}
public void Return(T instance)
{
_active.Remove(instance);
_pool.Enqueue(instance);
instance.gameObject.SetActive(false);
}
public void Return()
{
foreach (var instance in _active)
{
_pool.Enqueue(instance);
instance.gameObject.SetActive(false);
}
_active.Clear();
}
public void Destroy()
{
foreach (var instance in _active)
{
UnityEngine.Object.Destroy(instance);
}
while (_pool.Count > 0)
{
UnityEngine.Object.Destroy(_pool.Dequeue());
}
_active.Clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment