How do I link a .sks file to a .swift file in SpriteKit
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)
By the time of this answer (Xcode 8.2.1) the 'simple' way of doing this for scenes:
- Select the .sks file in your Project Navigator so the Graphic Editor is displayed
- Go to the Utilities Area (on the right hand side)
- Click on Custom class tab (icon looks like a contact card)
- In “Custom class” enter the name name of the class in your .swift file