使用Cocos2d的多个动画和纹理 - 如何从内存中删除纹理?

时间:2010-10-21 10:25:39

标签: iphone cocos2d-iphone

我正在编写一个应用程序,您可以在其中按下不同的按钮,并且角色会被动画化。问题是我有很多图像,所以我需要为每个动画使用一个纹理。因此我需要释放精灵表和框架现金,但它似乎没有工作。在应用程序崩溃之前,内存会被越来越多地分配。这是代码:

// **** DEFINE THE ANIMATION - EATING 1: ****

// Create a sprite sheet with all the images
CCSpriteSheet *spriteSheet = [CCSpriteSheet spriteSheetWithFile:@"Eating4.png"];

// This loads an image of the same name (but ending in png), and goes through the
// plist to add definitions of each frame to the cache.
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Eating4.plist"];    

[self addChild:spriteSheet];
///[self addChild:spriteSheet2];

// Load up the frames of our animation
NSMutableArray *eating1AnimFrames = [NSMutableArray array];
for(int i = 0; i <= 50; ++i) {
    if (i<=9){
        [eating1AnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"Eating4_000%d.png", i]]];
    }
    else if (i>9) {
        [eating1AnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"Eating4_00%d.png", i]]];
    }
}
CCAnimation *eatingAnim = [CCAnimation animationWithName:@"eating" delay:0.05f frames:eating1AnimFrames];

// Create a sprite for the mouse
CGSize winSize = [CCDirector sharedDirector].winSize;
self.mouse = [CCSprite spriteWithSpriteFrameName:@"Eating4_0000.png"];  
_mouse.position = ccp(winSize.width/2+20, winSize.height/2);
// Adjust the size of the Sprite:
[_mouse setScaleX: 1];
[_mouse setScaleY: 1];

//self.eatingAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:eatingAnim restoreOriginalFrame:NO]];
self.eatingAction = [CCAnimate actionWithAnimation:eatingAnim restoreOriginalFrame:NO];
[spriteSheet addChild:_mouse];

[_mouse runAction:_eatingAction];

我尝试释放这样的记忆:

[[CCTextureCache sharedTextureCache] removeAllTextures]; [[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFrames];

2 个答案:

答案 0 :(得分:2)

[[CCTextureCache sharedTextureCache] removeAllTextures];

你不想这样做!这将从内存中删除所有纹理,然后重新加载所有仍在使用中或下次使用它们的纹理。这会导致巨大的开销,并且通常会对您的游戏性能造成不利影响。

相反,只需通过调用

删除需要删除的纹理

[[CCTextureCache sharedTextureCache] removeTexture:tex];

为此,您还必须从Cocos2D节点层次结构中删除(释放)对动画的所有引用。

答案 1 :(得分:2)

调用removeUnusedTextures将是清除未使用纹理使用的内存的更好选择:

[[CCTextureCache sharedTextureCache] removeUnusedTextures];

或者您可以要求使用内部执行相同操作的CCDirector::purgeCachedData

[[CCDirector sharedDirector] purgeCachedData];