This method will unarchive an sks file and initialise it as whichever SKNode subclass it is called on. This means you can unarchive a file as an SKNode (so the root node will be an SKNode) and add it as a child to your scene. You can also unarchive a file as GameScene or any SKNode subclass.
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 like this:
let scene = GameScene.unarchiveFromFile("GameScene")! as GameScene
or
let levelStuff = SKNode.unarchiveFromFile("Level 1")!
self.addChild(levelStuff)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…