Using custom SKNodes in spritekit scene editor

▼魔方 西西 提交于 2019-12-13 12:06:39

问题


I want to create a level using my custom subclasses of SKNode. I tried adding an SKNode to the scene editor and using the "Custom Class" tab give the class that I want it to be but that did absolutely nothing. The node would still be empty and nothing would show when I run the simulator. Also, to make sure that the class actually works, I added an instance of it to the scene programmatically to see if it shows and it does.

How do I add my custom nodes to the scene through the scene editor?

Here's my custom class code:

class Player: SKSpriteNode {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        print("Test")
        self.addChild(SKSpriteNode(imageNamed: "Player.png"))
    }
}

回答1:


There are two things you need to do:

1) When setting the Custom Class you have to prefix the class name with your app's name; My_App_Name.MyClass for example, where _ represents a space.

2) Your SKNode subclass needs to implement required init?(coder aDecoder: NSCoder).


For example, in my project called 'MyGame':

class MyNode: SKSpriteNode {
    // Set this after the node has been initaliser by init(coder:)
    var someStat: Int = 0

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // To check it worked:
        print("Yup, all working")
    }
}



回答2:


I had the same problem in Xcode 8. It sounds stupid, but to apply a custom class I had to save the .sks file before running.

.sks files are not saved automatically, unlike text files or storyboards.



来源:https://stackoverflow.com/questions/31230666/using-custom-sknodes-in-spritekit-scene-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!