Entitas  0.40.0
Entitas is a super fast Entity Component System (ECS) Framework specifically made for C# and Unity
ObjectPool.cs
1 using System;
2 using System.Collections.Generic;
3 
4 namespace Entitas {
5 
6  public class ObjectPool<T> {
7 
8  readonly Func<T> _factoryMethod;
9  readonly Action<T> _resetMethod;
10  readonly Stack<T> _objectPool;
11 
12  public ObjectPool(Func<T> factoryMethod, Action<T> resetMethod = null) {
13  _factoryMethod = factoryMethod;
14  _resetMethod = resetMethod;
15  _objectPool = new Stack<T>();
16  }
17 
18  public T Get() {
19  return _objectPool.Count == 0
20  ? _factoryMethod()
21  : _objectPool.Pop();
22  }
23 
24  public void Push(T obj) {
25  if(_resetMethod != null) {
26  _resetMethod(obj);
27  }
28  _objectPool.Push(obj);
29  }
30  }
31 }