Hey, does anyone knows any good articles/examples/tutorials about making a good objects pool system ?
Mike done a live session back in April relating to object pooling, might be worth a watch
http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling
Here’s a simple generic pool class I use all over the place. It works with any object that has a publicly accesible constructor that doesn’t take parameters.
using System.Collections.Generic;
public class Pool<T> where T : new()
{
private List<T> pool;
public int Count
{
get
{
return pool.Count;
}
}
public Pool()
{
pool = new List<T>();
}
public T Get()
{
T item;
if (pool.Count > 0)
{
item = pool[0];
pool.RemoveAt(0);
}
else
{
item = new T();
}
return item;
}
public void Return(T itemToReturn)
{
pool.Add(itemToReturn);
}
}
For prefabs, I have a whole seperate pool class, since gameobjects have a few differences:
using System.Collections.Generic;
public class PrefabPool
{
private List<GameObject> pool;
private GameObject prefab;
private GameObject poolContainer;
public int Count
{
get
{
return pool.Count;
}
}
public PrefabPool(GameObject prefab)
{
if (prefab == null)
Debug.LogError("Attempt to create PrefabPool with null prefab.");
this.prefab = prefab;
}
// Must be initialized in the main game thread, since we're using GameObject.Find and GameObject.Instantiate.
public void Initialize()
{
pool = new List<GameObject>();
poolContainer = GameObject.Find("PrefabPool Container");
if (poolContainer == null)
{
poolContainer = GameObject.Instantiate(new GameObject);
poolContainer.name = "PrefabPool Container";
poolContainer.SetActive(false);
}
}
public GameObject Get()
{
if (pool == null)
Initialize();
GameObject item;
if (pool.Count > 0)
{
item = pool[0];
pool.RemoveAt(0);
}
else
{
item = GameObject.Instantiate(prefab);
}
return item;
}
public void Return(GameObject itemToReturn)
{
if (pool == null)
Initialize();
itemToReturn.transform.SetParent(poolContainer);
itemToReturn.SetActive(false);
pool.Add(itemToReturn);
}
}
Those should show you the basic principles of pooling. It’s really not too complicated.
This is a pretty decent example: http://blogs.msdn.com/b/dave_crooks_dev_blog/archive/2014/07/21/object-pooling-for-unity3d.aspx