Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

ios - Subclassing SKNodes created with SpriteKit .sks scene file

(this is for XCode 6 and iOS 8 beta 4)

Love the new SceneKit editor. I'm successfully loading the scene from .sks file into a custom SKScene class. However, objects inside it are instantiated as default classes (SKNode, SKSpriteNode, etc), and i'm not sure how to bind them to be instantiated as custom subclasses instead.

Currently, I'm getting around that by creating custom classes and linking to sprite nodes as a property, and that works ok

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Currently you are supposed to do it by name in the method added to the SpriteKit game templates. They cover this topic in the SpriteKit Best Practices video in WWDC 2014. It's easy to miss because the video has a lot in it.

Here is the method.

+ (instancetype)unarchiveFromFile:(NSString *)file {
    /* Retrieve scene file path from the application bundle */
    NSString *nodePath = [[NSBundle mainBundle] pathForResource:file ofType:@"sks"];
    /* Unarchive the file to an SKScene object */
    NSData *data = [NSData dataWithContentsOfFile:nodePath
                                          options:NSDataReadingMappedIfSafe
                                            error:nil];
    NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    [arch setClass:self forClassName:@"SKScene"];
    SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
    [arch finishDecoding];

    return scene;
}

It's a category on SKScene that includes a method to use NSKeyedUnarchiver to substitute the Class when loaded from the .sks file in the mainBundle. In iOS they add it to the GameViewController.m file and in OS X they add it to the AppDelegate.m file.

In here or in your individual SKNode subclasses, you can implement this. This is what he did below in his post. This was provided by Apple and covered in the WWDC video. I guess next year it will get handled better. In the meantime file a bug requesting SKNodes get something like IBDesignable for Scene Editor. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...