namespace NAK.PropSpawnTweaks; public class ObjectPool { public int Count { get; private set; } private readonly Queue _available; private readonly Func _createObjectFunc; public ObjectPool(int numPreallocated = 0, Func createObjectFunc = null) { _available = new Queue(); _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"); } }