- Home /
Instantiating GameObject from Generic Class
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.
Answer by Bunny83 · Jul 06, 2016 at 01:24 AM
The usual way when creating such a generic class is to provide a creation callback event. By default the pool would simply use "new". If you provide a callback it simply calls that callback to create a new instance. How that is done is up to the pool user.
public event Func<T> OnCreateRequest;
private T CreateInstance()
{
if (OnCreateRequest != null)
return OnCreateRequest();
var t = typeof(T);
if (typeof(Component).IsAssignableFrom(t))
return (new GameObject(t.Name)).AddComponent<T>();
return System.Activator.CreateInstance<T>();
}
This will use the "OnCreateRequest" callback if you provide one. If no callback is provided and the type is a Component it creates a new gameobject and attaches that component. If it's not a component derived type it simply uses the default constructor by using the Activator.
If the pool should pool a prefab you would simply do:
pool.OnCreateRequest += ()=>(YourPoolType)Instantiate(yourPrefab);
So everytime the pool calls "CreateInstance" internally it will actually call
(YourPoolType)Instantiate(yourPrefab)
If you have a "normal" class with a constructor that requires parameters you can do the same:
pool.OnCreateRequest += ()=> new YourPoolType(42,"some other parameter");
Your answer

Follow this Question
Related Questions
Object.Instantiate. , really? 4 Answers
Get method in script with Generic list 1 Answer
Checking if object intersects? 1 Answer
Instantiated Object being auto-deleted 0 Answers