I created a custom class in swift to manage my main menu for a game I'm making I linked it to the SKScene file and tried to create a constant to access the variable and I got this error: Cannot use instance member 'childNode' within property initializer.
import SpriteKit
import GameplayKit
class MainMenu: SKScene {
let startGameButton:SKSpriteNode = self.childNode(withName: "SpriteName")
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
Does anyone know whats happening? If not is there another way to access sprites.
Initial values for let
variables must be constants that can be initialized before the init()
method is executed. That in turn means they can't reference self
.
One workaround for that is making them lazy
instance variables, which get initialized when they are first used (which, by definition, can't happen before init()
has returned a reference to the object). In that case, the lazy variable would be initialized with the result from a closure.
Change:
let startGameButton:SKSpriteNode = self.childNode(withName: "SpriteName")
to
lazy var startGameButton:SKSpriteNode = self.childNode(withName: "SpriteName") as! SKSpriteNode
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments