Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

sprite kit - How do I link a .sks file to a .swift file in SpriteKit

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...