Best way to pool objects? (for speed)

Hi,

What is the best way to pool objects for re-use? I was thinking of something like disabling and enabling them instead of creating and destroying. Thinking of bullets, lots of aliens and such.

Would I be holding a list of references to these and then loop through to find one thats not used yet? Or are there better ideas for pooling in unity…

I usually use a stack based cache/pool for that sort of thing. When you need a bullet you pop one off the bullet stack and enable it. When the bullets life ends you just disable it and push it back onto the bullet stack.

Obviously it’s a bit more complicated than that but not much.

Would you mind sharing a really simple code snippet for this as I’d love to give it a try.

Thank you for the speedy reply :]

Just some pseudo-code:

var myPool : Array = new Array();


//to initialize your pool at some default size
function Initialize()
{
	for (var i : int = 0; i < TheSizeOfThePool; i++)
	{
		var myPooledObject : Bullet = Instantiate(....
		PoolObject(myPooledObject); //function declared below
	}
}


//when an object is destroyed and should return to the pool...
function PoolObject(pooledObject : Bullet)
{
	pooledObject.enabled = false;
	myPool.Push(pooledObject);
}

//when retrieving from the pool...
function GetPooledObject()
{
	if (myPool.Length == 0)
	{
		//ran out of objects
		//Add a new object to the pool?
		//Do nothing?
		//Up to you
	}
	else
	{
		var pooledObject: Bullet = myPool.Pop();
		pooledObject.enabled = true;
		return pooledObject;
	}
}

Thanks a lot, very helpful example :]

guys do mean " Pull" ? or u really use " Pool "? if yes , what’s it ?!

We mean pool. The idea of using a pool comes if creating/destroying many objects takes a lot of work, then pre-create a tonne of them (even… a “pool” of them!) then simply re-use them instead of constantly creating/destroying them!