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