EDIT: My own implementation of ObjectPool It probably could benefit some modification, I don’t claim it to be perfect, it just works for me.
Here is a tutorial from Unity http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling
The basic idea is to have a class that will store a list of game object, first you create:
List<GameObject>list;
public PoolSystem(int size, GameObject prefab){
list = new List<GameObject>();
for(int i = 0 ; i < size; i++){
GameObject obj = (GameObject)Instantiate(prefab);
list.Add(obj);
}
}
This is the constructor of your pool. It takes a size and what object you want to store.
Then it has a method to get the first of the list
public GameObject GetObject(){
if(list.Count > 0){
GameObject obj = list[0];
obj.RemoveAt(0);
return obj;
}
return null;
}
this one is simplified as if you are sure of the list you can skip the check and if you don’t want to return null, you can create a new obect to be added to the list.
The point of taking the first of a list is that you do not have to search for a free one while using the array.
The other part is to reassign the object to the pool:
public void DestroyObjectPool(GameObject obj){
list.Add(obj);
obj.SetActive(false);
}
Finally you may want to clear the pool:
public void ClearPool(){
for(int i = list.Count - 1; i > 0; i--){
GameObject obj = list.RemoveAt(i);
Destroy(obj);
}
list = null;
}
Though this last part is only useful if you need to clear a pool but if you do all properly you should not need that since the point of a pool is that you do not have to create and destroy, just create. The GC will take care of removing it all
I use List over Stack or Queue because it goes faster according to a test I did a while ago. You could also look here :
http://msdn.microsoft.com/en-us/library/ff458671%28v=vs.110%29.aspx
but I have never used nor seen ConcurrentBag apart from that example.