1
votes

What I want to do:

I want to use sprite sheets to load all my enemies in the game. They would have to be removed once they are either destroyed by the good guy or when they go off screen. I have 6-7 enemies some of which are animations. I will be reusing them multiple times. I wan to load and unload them effectively from the memory.

What I am doing:

I first load the spritesheets:

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Obstacles.plist"];
CCSpriteBatchNode *obstaclesspriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"Obstacles.pvr.ccz"];
[self addChild:obstaclesspriteSheet]; 

I have a class called BadBoys which handles the bad guys. Every time I want to create a bad guy I create an instance of the class. Inside the class I create the sprite and add it to the layer.

baddies[x] = [[BadBoys alloc] init];

//INSIDE THE CLASS
baddie = [CCSprite spriteWithSpriteFrameName:@"cannonball-hd.png"];

I remove the sprite from the layer when it gets destroyed and then release the instance of the class.

[self removeChild:[baddies[x] getBaddie] cleanup:YES]; //getBaddie returns the sprite
[baddies[x] release];

I know this is a good way to do it. What I want to know is if this is the most efficient way of doing this? I thought of another way of loading the image:

Load the image asynchronously to the CCTextureCache. Then create a sprite using the texture from the cache. Add it to a NSMutableArray which will hold all enemies that are alive Then when I dont need it anymore I can destroy it the following way:

CCTexture2D * texture = spriteName.texture;
[spriteName.parent removeChild:spriteName cleanup:YES];
[[CCTextureCache sharedTextureCache] removeTexture:texture];
[backgroundSprites removeObject:spriteName];

Is this a better method? Please share your views and suggestions. Thanks.

1

1 Answers

2
votes

What you're doing is good, as you said.

Your alternative is a terrible idea. I'll tell you why: you will want to avoid loading textures into memory and removing them from memory frequently during gameplay. Loading a texture from flash memory is slow. Removing the texture from memory also takes a little time, and is rather pointless if you have enough free memory available anyway.

Furthermore if you're using a spritesheet and you're removing one obstacle but try to remove the obstacle's texture (which is Obstacles.pvr.ccz) from memory as well, then the texture cache won't remove the texture from memory anyway. Because it's still being used by the spritesheet.

Lastly: premature optimization is the root of all evil.