Skip to content

Instantly share code, notes, and snippets.

@JulianG
Last active December 10, 2015 16:28
Show Gist options
  • Save JulianG/4460785 to your computer and use it in GitHub Desktop.
Save JulianG/4460785 to your computer and use it in GitHub Desktop.
General purpose AS3 Object Pool class
package
{
/**
* ObjectPool Class
* @author Julian
*/
public class ObjectPool
{
private var _list:Array;
public function ObjectPool(object_type:Class, qty:uint)
{
for (var i:int = 0; i < qry; i++)
{
_list.push( new object_type() );
}
}
public function getNextObject():*
{
var obj:* = _list.shift();
_list.push(obj);
return obj;
}
}
}
@JulianG
Copy link
Author

JulianG commented Jan 5, 2013

Usage:

var enemyPool:ObjectPool = new ObjectPool( Enemy, 15 );
// later on
var enemy:Enemy = enemyPool.getNextObject() as Enemy;

If you want the object pool to be globally accessible, you don't need static methods.
You can create a package-level variable like this:

// EnemyPool.as (file must be named like this, afaik)
package
{
  public var EnemyPool:ObjectPool = new ObjectPool( Enemy, 15 );
}

// later on, from anywhere in your code...

var enemy:Enemy = EnemyPool.getNextObject() as Enemy;

This way you can create many different instances of ObjectPool for different entities in your game without duplicating your code.

@FrancescoMaisto
Copy link

Nice one! There's a typo on line 13, qry instead of qty :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment