118 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Generic object pool for pure C# objects (DamageArgs, HealArgs, etc.)
/// Uses the same pattern as GameObjectPoolManager but for non-MonoBehaviour types.
///
/// USAGE:
/// - ObjectPool<DamageArgs>.Get() to get from pool
/// - ObjectPool<DamageArgs>.Release(args) to return to pool
///
/// REQUIREMENTS:
/// - Type T must have a parameterless constructor
/// - Type T should implement IResettable for proper cleanup (optional)
/// </summary>
public static class CObjectPool<T> where T : class, new()
{
private static Stack<T> _pool = new Stack<T>();
private static int _defaultCapacity = 32;
private static int _maxSize = 128;
private static bool _showDebugLogs = false;
static CObjectPool()
{
// Pre-warm the pool
for (int i = 0; i < _defaultCapacity; i++)
{
_pool.Push(new T());
}
if (_showDebugLogs)
Debug.Log($"ObjectPool<{typeof(T).Name}>: Initialized with {_defaultCapacity} objects");
}
/// <summary>
/// Get an object from the pool. Creates new if pool is empty.
/// </summary>
public static T Get()
{
T obj = _pool.Count > 0 ? _pool.Pop() : new T();
// Reset if implements IResettable
if (obj is IResettable resettable)
{
resettable.Reset();
}
if (_showDebugLogs)
Debug.Log($"ObjectPool<{typeof(T).Name}>: Get (pool size: {_pool.Count})");
return obj;
}
/// <summary>
/// Return an object to the pool.
/// </summary>
public static void Release(T obj)
{
if (obj == null)
{
Debug.LogError($"ObjectPool<{typeof(T).Name}>: Cannot release null object");
return;
}
// Reset before returning to pool
if (obj is IResettable resettable)
{
resettable.Reset();
}
// Don't exceed max size
if (_pool.Count < _maxSize)
{
_pool.Push(obj);
}
if (_showDebugLogs)
Debug.Log($"ObjectPool<{typeof(T).Name}>: Release (pool size: {_pool.Count})");
}
/// <summary>
/// Clear all pooled objects.
/// </summary>
public static void Clear()
{
_pool.Clear();
if (_showDebugLogs)
Debug.Log($"ObjectPool<{typeof(T).Name}>: Cleared");
}
/// <summary>
/// Get current pool statistics.
/// </summary>
public static (int pooled, int capacity, int maxSize) GetStats()
{
return (_pool.Count, _defaultCapacity, _maxSize);
}
/// <summary>
/// Configure pool settings. Call before first use.
/// </summary>
public static void Configure(int defaultCapacity = 32, int maxSize = 128, bool showDebugLogs = false)
{
_defaultCapacity = defaultCapacity;
_maxSize = maxSize;
_showDebugLogs = showDebugLogs;
}
}
/// <summary>
/// Interface for objects that need to reset their state when returned to pool.
/// Similar to IPoolable but for pure C# objects.
/// </summary>
public interface IResettable
{
void Reset();
}