How do I link a .sks file to a .swift file in Spri

2019-01-22 23:12发布

问题:

I saw that in XCode 6 there is a built in level editor. I could not find a lot of documentation on how to use it or how it works, but I was able to figure out how to use it to make SKSpriteNodes then link them to a .swift file using childNodeWithName(). When you make a new SpriteKit project, it starts with a GameScene.swift and a GameScene.sks. I was able to use these to make one level visually, then I could code for it in the GameScene.swift, but when I tried to make my own .sks and .swift file for a new level, I could not connect the .sks and the .swift file I had made. I tried following this tutorial 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 no errors came up, and then when I transitioned to the scene it transitioned properly, but nothing that I added visually to the .sks showed up in the simulator. Please help, I've spent hours researching solutions for this. The very few tutorials and forums that I was able to find about the level editor only talked about the GameScene.swift and .sks that start with a new SpriteKit project.

回答1:

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)


回答2:

By the time of this answer (Xcode 8.2.1) the 'simple' way of doing it is: Select the .sks file on the Project Navigator so the Graphic Editor shows up. Then going to the Utilities Area (Right Side), under the "Custom Class Inspector" tab; "Custom Class" field, type the name of the class in your .swift file.