在我的遊戲中,我必須在遊戲時間內更改場景背景。當我爲背景設置新紋理時,遊戲會放慢一會兒。爲了逃避這個我試圖預加載一個紋理異步,然後在主線程上顯示它。這就是我如何做到這一點:無法顯示異步加載的紋理
NSString *filename = [NSString stringWithFormat:@"res/src/level_%i/background.png", [GameLevel sharedGameLevel].currentLevelIndex + 1];
__block CCTexture2D *texture;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"FILENAME %@", filename);
[[CCTextureCache sharedTextureCache] addImage:filename];
NSLog(@"%@", [CCTextureCache sharedTextureCache]);
dispatch_async(dispatch_get_main_queue(), ^{
texture = [[CCTextureCache sharedTextureCache] textureForKey:filename];
[spareBackground setTexture:texture];
[dayBackground runAction:[CCSequence actions:fadeOut,[CCCallBlockN actionWithBlock:^(CCNode *node)
{
NSLog(@" TEXTURE %@", texture);
[dayBackground setTexture:texture];
CCFadeIn *fadeIn = [[[CCFadeIn alloc] initWithDuration:5] autorelease];
[dayBackground runAction:fadeIn];
}], nil]];
});
});
但不是背景,我總是收到儘管紋理黑屏已成功加載,它不是nil
。如果在不使用gcd的情況下在主線程上加載紋理,此代碼工作得很好。我錯過了什麼?
是你所有的NSLogs到最後一個顯示預期結果? – sergio 2013-02-12 09:00:56
和'sparebackground'與'dayBackground'有什麼關係?你想做什麼?都是分配產生黑色紋理? – sergio 2013-02-12 09:02:50
@sergio所有NSLogs顯示我期望看到的。 spareBackground恰好位於dayBackground底下。是的,這兩者都是空白 – 2013-02-12 09:05:14