I am using AndEngine to create a game.
I have randomly added sprites in my code that spawn just about every second.
I was informed that using a Generic Pool would save garbage collection in my case thats causing my game to lag at certain times.
So, here is what ive managed to come up with for my GenericPool..
public class FruitPool extends GenericPool<Sprite> {
private Sprite msprite;
public FruitPool(Sprite sprite) {
if (sprite == null) {
// Need to be able to create a Sprite so the Pool needs to have a TextureRegion
throw new IllegalArgumentException("The texture region must not be NULL");
}
msprite = sprite;
}
/**
* Called when a Bullet is required but there isn't one in the pool
*/
@Override
protected Sprite onAllocatePoolItem() {
return msprite;
}
/**
* Called when a Bullet is sent to the pool
*/
@Override
protected void onHandleRecycleItem(final Sprite sprite) {
msprite = sprite;
msprite.setIgnoreUpdate(true);
msprite.setVisible(false);
}
/**
* Called just before a Bullet is returned to the caller, this is where you write your initialize code
* i.e. set location, rotation, etc.
*/
@Override
protected void onHandleObtainItem(final Sprite fruit) {
fruit.reset();
}
}
So as you guys see ive created a pool that i am able to add a Sprite to.
The problem is i have a method that randomly picks a number between 1 and 6. And i use a Switch statment to chose which sprite will be added the the scene.
How could i do this with the GenericPool? Having it hold six different sprites and being able to choose which one is added to the scene?
I was thinking maybe i could create a method that will add each Sprite to the Pool in my game, and then im stuck at the part where i find a way to select which sprite is selected out of the pool, such as providing a int that it takes to pick a sprite.
Thanks for the help in Advance guys!
First of all, that is not how pools work.
In a pool, each call to
obtainshould obtain another un-recycled object. That means:Now,
sprite1andsprite2should not reference the same object. But with your implementation, they do and therefore it won’t work when you will obtain and use 2 items simultaneously.You should implement it like this:
This way, multiple sprites can be requested from the pool at the same time, and the pool will actually fill it’s purpose.
About your question, a pool is implemented using a stack, so you can not take out a specific item of it – only the one at the top. I recommend you then to create 6 different fruit pools, each one for another fruit type.
You should either extend
Spriteand include a fieldtype, for the type of the current fruit, so you’d know to which fruit pool you should send it when you are done, or use thesetUserDataandgetUserDatamethods to save information about the type of the current fruit.