Thursday, December 23, 2010

Object Pooling in Flixel

When I started to write my first game called Infinite Shooter I didn't realise that when you destroy an object in Flixel engine (using kill() function) it doesn't really disappear - it just "hang in the nowhere", still existing in allocated memory. Because of that after a few minutes of gameplay, when many planes arrived on and left the screen, I had a huge memory leak. Solution for that is making an object pool, where you can reuse killed objects and make a new ones from them. How can you achieve that in Flixel engine?

Imagine that your object pool will be keeping all of the enemy planes. First you have to instantiate FlxGroup.

private var _enemyPlanes:FlxGroup = new FlxGroup();

Next step is to make a function that returns EnemyPlane object. Basically it searches for a dead object in the object pool. If it finds one - it resets that object nad return it, but if every object in the pool is still alive, then a new object is instantiated and added to the object pool.

private function getEnemyPlaneSprite():EnemyPlane
{
  var enemyPlaneSprite:EnemyPlane = null;
  var enemyPlaneIndex:int = findDeadSprite(_enemyPlanes.members);
  
  if (enemyPlaneIndex != -1)
  {
    enemyPlaneSprite = _enemyPlanes.members[enemyPlaneIndex];
    enemyPlaneSprite.reset(0, 0);  
  }
  else
  {
    enemyPlaneSprite = new EnemyPlane();
    _enemyPlanes.add(enemyPlaneSprite);
  }
  
  return enemyPlaneSprite;
}

In the snippet above you can find findDeadSprite() function - here you can see the code for it.

private function findDeadSprite(spriteArray:Array):int
{
  var index:int = -1;
  
  for (var i:int = 0; i < spriteArray.length; i++)
  {
    if ((spriteArray[i].dead == true) && (spriteArray[i].exists == false))
    {
      index = i;
      break;
    }
  }
  
  return index;
}

Now when you need new EnemyPlane object you just need to use getEnemyPlaneSprite() function.

var enemyPlane:EnemyPlane = getEnemyPlaneSprite();

I don't know if it is the best solution for that problem, but it works fine for me, and of course this stopped the huge (when I say it I mean really huge) memory leak in my application.

No comments:

Post a Comment