SKTexture预加载

当使用spritekit preloadTextures函数预加载纹理时,它会将提供的数组中的所有纹理一次加载到内存中。

如果你没有能力通过“加载屏幕”来分割游戏中的关卡,但是不同的图像文件有不同的关卡,那么怎样才能避免将所有图像一次存储在内存中而不会牺牲帧spritekit在需要时加载图像的速度?

你可以使用方法来创build一个单例类,用于加载和卸载特定于当前正在玩的级别的资源。 例如,如果你需要为一级加载纹理a,b和c,为二级join纹理x,y和z,你可以使用一个方法-(void)loadLevelOneTextures;-(void)loadLevelTwoTextures; 以及一个-(void)unloadLevelOneTextures;-(void)unloadLevelTwoTextures;

这样,你可以告诉单身人士在你需要的时候加载纹理,当你完成的时候告诉它释放它们。

 //GameTextureLoader.h // @import SpriteKit; @import Foundation; @interface GameTextureLoader : NSObject @property (strong, nonatomic)NSMutableArray *levelOneTextures; @property (strong, nonatomic)NSMutableArray *levelTwoTextures; + (GameTextureLoader *)sharedTextures; - (void)loadLevelOneTextures; - (void)unloadLevelOneTextures; - (void)loadLevelTwoTextures; - (void)unloadLevelTwoTextures; 

并执行:

 //GameTextureLoader.m // #import "GameTextureLoader.h" @implementation GameTextureLoader + (GameTextureLoader *)sharedTextures{ static dispatch_once_t onceToken; static id sharedInstance; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } - (instancetype)init{ self = [super init]; if (self) { self.levelOneTextures = [[NSMutableArray alloc] init]; self.levelTwoTextures = [[NSMutableArray alloc] init]; return self; } else{ exit(1); } } - (void)loadLevelOneTextures{ //Order of images will determin order of textures NSArray *levelOneImageNames = @[@"imageA", @"imageB", @"imageC"]; for (NSString *image in levelOneImageNames){ SKTexture *texture = [SKTexture textureWithImageNamed:image]; [self.levelOneTextures addObject:texture]; } } - (void)loadLevelTwoTextures{ //Order of images will determin order of textures NSArray *levelTwoImageNames = @[@"imageX", @"imageY", @"imageZ"]; for (NSString *image in levelTwoImageNames){ SKTexture *texture = [SKTexture textureWithImageNamed:image]; [self.levelTwoTextures addObject:texture]; } } - (void)unloadLevelOneTextures{ [self.levelOneTextures removeAllObjects]; } - (void)unloadLevelTwoTextures{ [self.levelTwoTextures removeAllObjects]; } 

你会为每个级别做这个,然后访问纹理,你会做这样的事情。 (一定要先导入GameTextureLoader.h)

 GameTextureLoader *loader = [GameTextureLoader sharedTextures]; [loader loadLevelOneTextures]; SKSpriteNode *node = [SKSpriteNode spriteNodeWithTexture:loader.levelOneTextures[0]]; [self addChild:node];