28

I'm trying to create class which is a subclass of SKSpriteNode and I want to add other properties and functions to it. But in the first step I faced an error. Here's my code:

import SpriteKit

class Ball: SKSpriteNode {
    init() {
        super.init(imageNamed: "ball")
    }
}

It's not a compile error, It's run-time error. It says: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) and fatal error: use of unimplemented initializer 'init(texture:)' for class Project.Ball.

How can I fix it?

TheNeil
  • 3,321
  • 2
  • 27
  • 52
Potter
  • 855
  • 2
  • 9
  • 9

1 Answers1

49

You have to call the designated initializer for SKSpriteNode. I'm actually surprised you didn't get another error about not full implementing SKSpriteNode, are you using an older Xcode6 beta maybe?

Since you have to use the designated initializer, you need to call super.init(texture: '', color: '', size: '').

It would be something like this:

class Ball: SKSpriteNode {
    init() {
        let texture = SKTexture(imageNamed: "ball")
        super.init(texture: texture, color: nil, size: texture.size())
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Note: I also added the init for NSCoder which Xcode will require.

mtmk
  • 6,176
  • 27
  • 32
Mike S
  • 41,895
  • 11
  • 89
  • 84
  • 3
    `SKSpriteNode` has no `init()` initializer, so you shouldn't have `override` in the delcaration. – Christopher Pickslay May 09 '15 at 18:19
  • Can someone help me and show how this Ball Class gets initialized in another Swift File? I cant get it running :-/ – boehmatron Feb 23 '16 at 21:19
  • 4
    Color is not nullable on SKSpriteNode's designated initializer, so you need to use `UIColor.clearColor()` when calling super.init – leolobato Apr 20 '16 at 11:46
  • 1
    SKColor.clearColor() works as an alternative to what leolobato wrote. It is a part of the SpriteKit library. – JKRT Aug 18 '16 at 22:56
  • 1
    Latest Xcode (10.0) won't accept nil as color. I had to use .clear instead (based on leolobato's and JKT's comments) – mtmk Oct 27 '18 at 14:52
  • Sorry @MikeS; edited your answer then rolled back. not sure if you want to keep the code in line with the latest Xcode or not. – mtmk Oct 27 '18 at 14:56