Reputation: 55
Am new to swift 2 and i got stuck in passing a variable from one class to another.
I have a class "GameScene" in it I have a public variable score and it keeps updating in update function. I want to send the score value at the time when two nodes collide with each other. Once it collides I go to another scene using "mainview .presentScene(gameoverScene)" syntax. I want the updated score in gameoverscene.
I tried using "private let _gameScene = GameScene()" in gameoverscene and passing it to a lable using "finalscore.text = String( _gameScene.finalScore)" the variable what I get is O which I declared at the beginning but not the updated score. Pls help me in finding out the solution.
Upvotes: 3
Views: 1060
Reputation: 544
I used NSUserDefaults
to handle this.
So, in the GameScene
just after the class GameScene
is declared (and not in any function) I used
var score = Int()
var defaults = NSUserDefaults.standardUserDefaults()
Then in the didMoveToView(view: SKView)
function in the same class, I used
defaults.setInteger(0, forKey:"score")
So that whenever GameScene
is presented, the current score resets to 0 before you start the game.
Then in your collision function, before the GameOver
scene is about to be presented (but still in the GameScene
class), you use (after your score has been increased or decreased)
defaults.setInteger(score, forKey:"score")
This will set the current score
to the key "score"
in NSUserDefaults
.
Finally, in the GameOver
scene, before you present the score, you can say
let scoreFromGameScene = NSUserDefaults.standardUserDefaults().integerForKey("score")
label.text = "\(scoreFromGameScene)" //Or whatever you use to present the score
This will make sure that you get the current score from the GameScene
so that you can use it in your GameOver
scene. Since the key "score"
will always have SOME integer value, we can retrieve the value without error.
Hope that helps :)
Upvotes: 2
Reputation: 59506
If your GameScene
has a score
property declared as below
class GameScene: SKScene {
var score = 0
}
then from any node of you game (that has been added to the main scene) you can retrieve you scene using the scene
property. So you can do something like that.
class MyNode: SKNode {
func foo() {
guard let gameScene = self.scene as? GameScene else {
fatalError("This node does not belong to a GameScene")
}
gameScene.score = 123
}
}
By you comment I understand you want to share the score
value among multiple scenes. There are several approach to achieve this. One of the easiest if the following.
Saving
NSUserDefaults.standardUserDefaults().setInteger(123, forKey: "score")
Reading
let score = NSUserDefaults.standardUserDefaults().integerForKey("score")
Please note that this way the value is stored on persistent storage and when you restart the app the value is still available.
Upvotes: 3