msqar msqar - 1 year ago 57
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 Source

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.


var score:Int = 0


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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download