I create my sprite kit games programmatically and the sks files end up just confusing me.
Is there a way to load or create a tile map node without having to use the sks/scene file?
I figured out a way to to do it:
3) Add this extension to load that scene file in your current scene:
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = Bundle.main.path(forResource: file as String, ofType: "sks") {
let sceneData = NSData(contentsOfFile: path)
let archiver = NSKeyedUnarchiver(forReadingWith: sceneData as! Data)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! SKNode
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
Then grab the tile map from the sks file. Weird trick is that you have to remove it from its parent first:
guard
let tileScene = SKScene.unarchiveFromFile(file: "TileMaps"),
let testMap = tileScene.childNode(withName: "Dungeon1")
as? SKTileMapNode else {
fatalError("Background node not loaded")
}
self.testMap = testMap
self.testMap.removeFromParent()
self.testMap.zPosition = 1200
self.addChild(testMap)