msqar msqar - 4 months ago 13
iOS Question

What's the cleanest way to call a method from one SKScene to another in Swift?

So I got in my game 3 different scenes: MenuScene, GameScene and GameOverScene.

I would like to know how I can get the score variable located in GameScene from GameOverScene so I can show it up there after the player loses.

So in GameScene, I created this simple getter:

func getScore() -> Int {
return self.score
}


But if I try to do GameScene.getScore() from a different Scene I get an error.

Tried using "class" before func

class func getScore() -> Int {
return self.score
}


But that also gives me an error from GameScene saying:


"Instance member 'score' cannot be used on type GameScene"


So how's the best way to do it? I don't want to create a global variable for this, it would be ugly.

Thanks in advance.

Answer

This is quite easy actually. When you segue to the new scene, you can also pass in a variable with it... Here is an example.

GameOverScene.swift

var score:Int = 0

GameScene.swift

var score:Int = THE USERS SCORE    

func segue(){
    let gameScene = GameOverScene(size: self.size)
        gameScene.score = score
        let transition = SKTransition.doorsCloseHorizontalWithDuration(0.5)
        gameScene.scaleMode = SKSceneScaleMode.AspectFill
        self.scene!.view?.presentScene(gameScene, transition: transition)
}