Search code examples
iosxcodeswiftskscene

How to create initializer for subclass of SKScene


I am Swift and Xcode, trying to make a simple text adventure for iOS. The game starts at the GameScene that has a Start button. When it registers a tap on the button, it moves to the first PlayScene instance. It has some text (a description of the scene) and two options (buttons A and B). When it registers a tap on a button, it moves to the corresponding PlayScene instance. And so on until it reaches an EndScene that has only text and a button to restart.

My idea was to implement an initializer for PlayScene that would take the text that a scene is supposed to have and the next scenes that should follow. So in my PlayScene.swift I added the following:

let sceneText: String
let nextSceneA: PlayScene
let nextSceneB: PlayScene

init(sceneText: String, nextSceneA: PlayScene, nextSceneB: PlayScene) {
    self.sceneText = sceneText
    self.nextSceneA = nextSceneA
    self.nextSceneB = nextSceneB
}

I get this error:

'required' initializer 'init(coder:)' must be provided by subclass of 'SKScene'

Does that mean there is no way to create a custom initializer for a subclass of SKScene? How else can I implement a sequence of scenes like that?


Solution

  • You need to implement init(coder:), even if all it does is return an error.

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