Using a .sks File to Compose a Complex Object and an SKScene File

Is it possible to use SceneEditor to build and create a complex subclass of SKSpriteNode, load this information and create a custom object in your scene based on the sks file?

My scenario is that I have popup dialogs (which are nothing more than subclasses of SKSpriteNodes) with lots of children in the dialog box. I was hoping to put it in the scene editor, similar to how I lay out SKScene, and then present it in my scene when necessary.

I understand that I could just create this object in my GameScene.sks file, but found that they could easily be cluttered, and thought it might be a more convenient way to save these dialogs if each of them has its own sks file .

I tried to extend SKSpriteNode to access a file similar to a scene file, but it did not work

if let teamDialog = SKSpriteNode.spriteWithClassNamed(className: "TeamDialog", fileName: "TeamDialog.sks") { }

extension SKSpriteNode {

    static func spriteWithClassNamed(className: String, fileName: String) -> SKSpriteNode? {

        guard let dialog = SKSpriteNode(fileNamed: fileName) else {
                return nil
        }

        return dialog
    }
}

enter image description here

+1
source share
1 answer

You can use this delegate https://github.com/ice3-software/node-archive-delegate

Or, smt, how fast it is:

class func unarchiveNodeFromFile(file:String)-> SKNode? {
    if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
        var fileData = NSData.dataWithContentsOfFile(path, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)
        var archiver = NSKeyedUnarchiver(forReadingWithData: fileData)
        archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKNode")
        let node = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as SKNode
        archiver.finishDecoding()
        return node
    } else {
        return nil
    }
}

UPDATE for Swift 3 and fix the class:

func unarchiveNodeFromFile(file:String)-> SKNode? {
    if let path = Bundle.main.path(forResource: file, ofType: "sks") {
        let fileData = NSData.init(contentsOfFile: path)
        let archiver = NSKeyedUnarchiver.init(forReadingWith: fileData as Data!)
        archiver.setClass(SKNode.classForKeyedUnarchiver(), forClassName: "SKScene")
        let node = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! SKNode
        archiver.finishDecoding()
        return node
    } else {
        return nil
    }
}
+1
source

Source: https://habr.com/ru/post/1669618/


All Articles