2010-10-21 28 views
1

我正在編寫一個應用程序,您可以按下不同的按鈕並且角色會變成動畫。問題是我有很多圖像,所以我需要爲每個動畫使用一個紋理。因此我需要發佈精靈表和框架現金,但它似乎沒有工作。內存分配越來越多,直到應用程序崩潰。下面是代碼:多個動畫和紋理與Cocos2d - 如何從內存中刪除紋理?

// **** 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
[[CCTextureCache sharedTextureCache] removeAllTextures]; 

你不想這樣做!這會從內存中刪除所有紋理,然後重新加載所有仍在使用或下次使用它們的紋理。這會導致很大的開銷,並且對遊戲的性能通常不利。

相反,只取出紋理,你需要通過調用刪除:

[CCTextureCache sharedTextureCache] removeTexture:TEX]。

爲此,您還必須從Cocos2D節點層次結構中刪除(釋放)所有對動畫的引用。

+0

謝謝!你有一個例子(聲明紋理,去除紋理和所有參考)? – 2010-10-26 08:00:50

2

調用removeUnusedTextures將是清理未使用的材質使用的內存更好的選擇:

[[CCTextureCache sharedTextureCache] removeUnusedTextures]; 

也可以要求使用CCDirector::purgeCachedData,做內部同樣的事情:

[[CCDirector sharedDirector] purgeCachedData];