在我的游戏中,我必须在游戏期间更改场景的背景。当我为背景设置新纹理时,游戏会变慢一会儿。为了避免这种情况,我试图异步预加载纹理,然后在主线程上显示它。我就是这样做的:
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,则此代码可以正常工作。我错过了什么?