Search code examples
swiftsprite-kitsubclassskspritenode

How to create subclass of SKSpriteNode in Swift 3


I've seen lots of similar questions to mine but they all seemed to be for older versions of Swift or for very different situations. In any case, none of the solutions worked for me.

I am building a simple SpriteKit game. Basically, all I want to do is add an attribute to the SKSpriteNode class: e.g.

let Ci = SKSpriteNode(imageNamed: "CBlob")
Ci.name = "C1"
Ci.pitch = "middle C"

Currently, setting the name attribute works fine because SKSpriteNode has a name attribute. In Python I would just be able to declare the pitch attribute when instantiating the object. However, in Swift to add the pitch attribute I have tried to create a SKSpriteNode subclass.

class Blob : SKSpriteNode {
var pitch = "middle C"
}

However, I can't figure out how to initialise an instance of Blob. e.g.

let Ci = Blob(imageNamed: "CBlob")

I feel like I've tried every combination of super, override etc. but all result in errors.

Many thanks in advance.


Solution

  • Turns out my code is fine, the bugs were due to something else. If anyone sees this - it is now that easy to add new attributes to a subclass - you don't have to faff around with super inits etc.

    print(Ci.pitch) 
    

    will now give "middle C".