Search code examples
swiftsprite-kitsubclassing

Cannot create subclass of SKSpriteNode


Trying to subclass SKSpriteNode so make my game code cleaner, and I'm obviously not understanding something. Here's a very simple example: I create a new Swift file called Alien.swift with the following contents:

import SpriteKit

class Alien: SKSpriteNode {

}

In my game, I do:

    let alienSprite: Alien = Alien()
    print("It's an \(alienSprite)")

and I get:

It's an (SKSpriteNode) name:'(null)...'

Even Xcode says it's an 'aliensSprite':

enter image description here

Why, at run-time, is it not printing that it's an 'alienSprite'?

Edit: incorporating one of my comments here - I'm actually picking up the sprite from my .sks file, where I placed it with the scene editor and set its custom class. I try to pick it up with:

let alien = childNodeWithName("alien") as! alienSprite 

but I get the error:

Cannot cast SKSpriteNode to alientSprite

Solution

  • Take notice to the state of your scene file. If you see it shaded, this means it has not saved yet. If you compile your code while still in the scene editor, the save will not happen, so be sure to hit cmd + s to save prior to compiling. enter image description here

    Now in case people are trying to figure out why class names are not saving, make sure you hit ENTER or leave the text field and go to another textfield to ensure that the class name saves, otherwise it will revert back to an older state.

    enter image description here