使用spritekit preloadTextures函数预加载纹理时,它将立即将提供的数组中的所有纹理加载到内存中。
如果您没有能力通过“加载屏幕”在游戏中拆分关卡,但确实拥有彼此不同的关卡,且图像文件彼此不同,那么如何在不牺牲帧数的情况下避免一次将所有图像存储在内存中需要什么时候spritekit加载图像?
您可以创建一个单例类,该类具有用于加载和卸载当前正在播放的级别的资源的方法。例如,如果您需要为级别1加载纹理a,b和c,为级别2加载纹理x,y和z,则可以使用method-(void)loadLevelOneTextures;
和a-(void)loadLevelTwoTextures;
以及a-(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];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句