Search code examples
androidobjectspriteandengineobjectpool

Andengine - Object pool or generic pool optimisation


I am creating a game which generates many sprites at some point such as bullets. I am using object pooling which is generic pool in andengine. But the problem I am facing is it lags when the object are created for the first time. As for the first time , when the object is attached to scene. It lags when I am attaching 100 sprites at a time.

So I was thinking if its possible to load all the required objects and load it to the pool while in loading scene.

for now my code is as follows..

bullets = bullet_pool.obtainPoolItem();

if(!bullets.hasParent())
    {
    Presentscene.attachChild(bullets);
    }

Please suggest me some ideas.

Can I load a 100 objects (sprite) in the pool before the game, So that It wont lag in the middle of the game to create objects fresh for the pool.


Solution

  • You can pre-load the amount of bullets you want during the loading sequence of the game. Something like this:

    private void preloadBullets(){
        Bullet[] bulletArr = new Bullet[1000];
        // Create the new bullets
        for (int i=0; i<1000; ++i){
            bulletArr[i] = bullet_pool.obtainPoolItem();
        }
        // Recycle all bullets
        for (int i=0; i<1000; ++i){
            bullet_pool.recyclePoolItem(bulletArr[i]);
        }
    }
    

    This way, if you call preloadBullets before your game runs, you'll have 1,000 bullets recycled in the pool for fast item obtaining.