I am in the process of implementing a resource pool so I can reuse my objects rather than creating/destroying them constantly. I would like it to work with unity GameObjects and also any other type. This is the gist of what I have so far:
public class ResourcePool <T> {
// initializes the pool with a number of items
public void Init(int startingSize) {}
// removes and returns unused item from pool
public T GetItem() {}
// puts item back into pool
public void ReturnItem(T item) {}
// Deletes excess unused items in pool
public void Trim() {}
// creates and adds a number of new items to pool
private void addItems(int num) {}
// removes and deletes a number of items from pool
private void removeItems(int num) {}
}
My problem Is that I don’t see an easy way to customize Instantiation or Deletion of objects in the pool. Obviously with most objects, a simple “new T()” would work fine. But when T is a MonoBehavior on a GameObject, or its constructor takes arguments, it gets trickier.
The only way to do it that I have come up with so far is to create child classes for each resource pool type in order to override the “addItems” and “removeItems” functions. It works, but at that point, why use generics?
How can I do this? Am I overcomplicating this or overlooking something simple? Any Ideas would be great.