This method will unpack the sks file and initialize it like any SKNode subclass to which it is called. This means that you can unzip the file as SKNode (so the root node will be SKNode) and add it as a child to your scene. You can also unlock the file as GameScene or any subclass of SKNode.
extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as SKNode archiver.finishDecoding() return scene } else { return nil } } }
Use it as follows:
let scene = GameScene.unarchiveFromFile("GameScene")! as GameScene
or
let levelStuff = SKNode.unarchiveFromFile("Level 1")! self.addChild(levelStuff)
Okapi
source share