gpt4 book ai didi

iphone - 无法显示异步加载的纹理

转载 作者:行者123 更新时间:2023-11-29 04:08:24 24 4
gpt4 key购买 nike

在我的游戏中,我必须在游戏过程中更改场景的背景。当我为背景设置新纹理时,游戏速度会减慢一会儿。为了避免这个问题,我尝试异步预加载纹理,然后在主线程上显示它。我就是这样做的:

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,则此代码可以正常工作。我错过了什么?

最佳答案

我的怀疑是CCTextureCache不是线程安全的(并且作为共享对象,它需要线程安全才能从另一个线程安全地调用)。

另一方面,Cocos2d 已经提供了异步加载纹理的机制,因此您可以使用它们。这应该是签名:

[[CCTextureCache sharedTextureCache] addImageAsync:filename target:self selector:@selector(textureLoaded:)];

关于iphone - 无法显示异步加载的纹理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14828589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com