Ios 将变量传递到场景
我正在尝试将一个预加载的Ios 将变量传递到场景,ios,objective-c,sprite-kit,Ios,Objective C,Sprite Kit,我正在尝试将一个预加载的SKTextures数组从SpriteKit场景的UIViewController传递到初始化后的场景中 但是,我似乎无法自定义SKScene在数组中传递的初始化方法 这就是我想做的: @interface MyViewController () @property (nonatomic, strong) NSArray *texturePack; @end *我不知道如何在初始化self.texturePack之前将其传递到场景? 如果有人对如何在初始化变量时将
SKTexture
s数组从SpriteKit场景的UIViewController
传递到初始化后的场景中
但是,我似乎无法自定义SKScene
在数组中传递的初始化方法
这就是我想做的:
@interface MyViewController ()
@property (nonatomic, strong) NSArray *texturePack;
@end
*我不知道如何在初始化self.texturePack之前将其传递到场景?
如果有人对如何在初始化变量时将变量传递给SKScene有任何建议,我将不胜感激。您必须在SKScene的子类中公开声明该属性
@interface MyScene : SKScene
@property (nonatomic, strong) NSArray *texturePack;
@end
然后,在创建场景的实例时。为新声明的属性设置一个值。执行此操作后,可以从场景实例中访问阵列
SKView * skView = (SKView *)self.spriteView;
if (!skView.scene) {
skView.showsFPS = YES;
skView.showsNodeCount = YES;
MyScene *scene = [MyScene initWithSize:skView.bounds.size];
[scene setTexturePack:someArrayReference];
scene.scaleMode = SKSceneScaleModeAspectFill;
// Present the scene.
[skView presentScene:scene];
}
编辑:您是否希望创建一个将数组作为参数的自定义初始化方法?如果是这样,请将其添加到场景子类中,并在场景标题中对其进行公开声明
- (instancetype)initWithSize:(CGSize)size andCustomParameter:(NSArray *)theArray {
self = [super initWithSize:size];
if (self) {
// do something with the array on iniitialization
}
return self;
}
如果我是你,我会创建一个单例类,将该数组作为属性传递,然后从那里访问它
//SharedTextures.h
@interface SharedTextures : NSObject
@property (strong, nonatomic)NSArray *textures;
@end
//sharedTextures.m
+ (instancetype)sharedInstance{
static dispatch_once_t onceToken;
static id sharedInst;
dispatch_once(&onceToken, ^{
sharedInst = [[self alloc] init];
});
return sharedInst;
}
- (id)init{
self.textures = [self loadTextures]
}
现在,当任何人需要这些纹理时,您可以调用:
SharedTextures *shared = [SharedTextures sharedInstance];
SKTexture *texture = shared.textures[//indice of texture];
这样做的好处是,您只需加载一次纹理,而不需要在场景之间传递纹理。这两种方法都是有效的,但这提供了更好的代码封装,因为您现在可以将纹理加载代码全部放入这一类中,因此它位于中心位置。感谢您为我准备此答案,但这是我通常会遵循的方法,它不起作用,因为在初始化场景时需要访问变量。也就是说,我似乎需要子类
SKScene
来修改初始化方法,但我找不到一个简单的方法来进行修改,因为SKScene和factory子类之间的类初始化方法不同。
SharedTextures *shared = [SharedTextures sharedInstance];
SKTexture *texture = shared.textures[//indice of texture];