Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 478
Rudi Avatar asked Aug 04 '14 16:08

Rudi


1 Answers

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. :)

like image 101
uchuugaka Avatar answered Sep 21 '22 05:09

uchuugaka