mirror of
https://github.com/NotAKidoS/NAK_CVR_Mods.git
synced 2025-09-02 06:19:22 +00:00
45 lines
No EOL
974 B
C#
45 lines
No EOL
974 B
C#
namespace NAK.PropSpawnTweaks;
|
|
|
|
public class ObjectPool<T>
|
|
{
|
|
public int Count { get; private set; }
|
|
|
|
private readonly Queue<T> _available;
|
|
private readonly Func<T> _createObjectFunc;
|
|
|
|
public ObjectPool(int numPreallocated = 0, Func<T> createObjectFunc = null)
|
|
{
|
|
_available = new Queue<T>();
|
|
_createObjectFunc = createObjectFunc;
|
|
|
|
if (numPreallocated > 0) Give(MakeObject());
|
|
}
|
|
|
|
public T Take()
|
|
{
|
|
T t;
|
|
if (_available.Count > 0)
|
|
{
|
|
t = _available.Dequeue();
|
|
Count--;
|
|
}
|
|
else
|
|
{
|
|
t = MakeObject();
|
|
}
|
|
|
|
return t;
|
|
}
|
|
|
|
public void Give(T t)
|
|
{
|
|
_available.Enqueue(t);
|
|
Count++;
|
|
}
|
|
|
|
private T MakeObject()
|
|
{
|
|
if (_createObjectFunc != null) return _createObjectFunc();
|
|
throw new InvalidOperationException("Cannot automatically create new objects without a factory method");
|
|
}
|
|
} |