Unarchived Node does not appear when adding a parent to SpriteKit

I used to ask if I could use the Scene editor to create complex SKSpriteNodes and just use it to build SKScenes. Using @Anton Rogachevskyi of the previous question, I started using unarchiveNodeFromFile to find the .SKS file. It loads the sks file, as expected, but when I try to add it to the current scene, nothing appears. If I break the addChild line and look at the object that it displays in the preview window, so I know that it finds the correct file. Inside the sks file there is a custom dialog class and setting breakpoints in "required init?" (Coder aDecoder: NSCoder) "I can say that the user object is getting the correct initialization.

dialogue created in scene editor

, , init

class TeamDialog: SKSpriteNode {

init(size: CGSize) {
    super.init(texture: nil, color: .red, size: size)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    setup()
}

func setup() {

    let pinkBox = SKSpriteNode(color: .magenta, size: CGSize(width: 100, height: 100))
    pinkBox.zPosition = 500
    addChild(pinkBox)
}
}

, , ,

private func displayDialog() {

    if let wtf = unarchiveNodeFromFile(file: "TeamDialog")! as SKNode? {

        let layer = SKSpriteNode(color: .clear, size: self.size)
        layer.zPosition = 5000
        layer.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
        addChild(layer)

        for child in wtf.children {
            print("child \(child.name)")
            if let teamDialog = child as? TeamDialog {
                teamDialog.removeFromParent()
                layer.zPosition = 1
                layer.addChild(teamDialog)
            } 
        }
    }
}

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
    }
}

object preview

, , , .

, - - , ?

.

sks ( node) , sks

+3
1

, , SKReferenceNode. SKReferenceNode , , , , .

, (x = -1500), , scene.sks, , . sks, . , , , sks , CGPoint (x: 0, y: 0) . , , , , . , , SKReferenceNode, .

, sks !

- , , sks, . , sks , sks ​​ .

    let path = Bundle.main.path(forResource: "TeamDialog", ofType: "sks")
    let dialogScene = SKReferenceNode (url: URL (fileURLWithPath: path!))
    if let teamDialog = dialogScene.childNode(withName: "//teamDialog") as? TeamDialog {
        teamDialog.setup(scene: self)
        teamDialog.position = CGPoint(x: 0, y: 0)
        dialogScene.zPosition = 5000
        addChild(dialogScene)
    }
+2

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


All Articles