How to link .sks file to .swift file in SpriteKit

I saw that Xcode 6 has a built-in level editor. I could not find much documentation on how to use it or how it works, but I was able to figure out how to use it so that SKSpriteNodes associate them with the .swift file using childNodeWithName (). When you create a new SpriteKit project, it starts with GameScene.swift and GameScene.sks. I could use them to make one level visually, then I could encode it in GameScene.swift, but when I tried to create my own .sks and .swift file for a new level, I could not connect .sks and the .swift file, which i did. I tried following this guide exactly:

http://www.techotopia.com/index.php/An_iOS_8_Swift_Sprite_Kit_Level_Editor_Game_Tutorial#Creating_the_Archery_Scene

When I connected the two files, errors did not appear, and then, when I went to the stage, it went right, but nothing that I added visually in .sks appeared in the simulator. Please help, I spent hours researching solutions for this. The very few tutorials and forums that I could find about the level editor spoke only about GameScene.swift and .sks, which start with the new SpriteKit project.

+7
swift xcode6 sprite-kit
source share
2 answers

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) 
+5
source share

At the time of the response (Xcode 8.2.1), the “simple” way to do this is: Select the .sks file in the Project Navigator to display the graphical editor. Then go to the "Utilities" area (right side) under the "Custom Inspector" tab; In the Custom Class field, enter the class name in the .swift file.

+2
source share

All Articles