Lucas Farleigh
Lucas Farleigh

Reputation: 1178

My Highscore amount keeps going up and down. Swift SpriteKit

I have a spritekit game which I have a highscore in. It uses NSUser Default. But I get the highscore 2, and then I close the app completely, and then open it it shows my highscore 2, and then get one as a score. It remains as 2. However, I close the app again and open it, it shows the highscore 1. Why does it do this? This is my code. Does the if condition not work? Note: This is just narrowed down to Highscore code.

import SpriteKit

//In the DidMoveToView function
if let Highscore1 = defaults.stringForKey("Highscore"){
    HighScoreLabel.text = "HIGHSCORE: \(Highscore1)"
}
//In the touches began func
//Making what happens when the User Fails and a new highscore is achieved

if Score > highscore {

    defaults.setObject("\(Score)", forKey: "Highscore")

}

Thank you in advance

Upvotes: 0

Views: 49

Answers (1)

Midhun MP
Midhun MP

Reputation: 107131

The issue is you are reading the highscore from NSUserDefaults and showing it in the HighScoreLabel. But you didn't assigned/stored the value in highscore variable, because of that it remains at 0. That makes the following condition true when you open the app and plays for the first time:

if Score > highscore {
    defaults.setObject("\(Score)", forKey: "Highscore")
}

You need to change the high score reading part like:

if let Highscore1 = defaults.stringForKey("Highscore") {
    HighScoreLabel.text = "HIGHSCORE: \(Highscore1)"

    // Storing current high score to variable
    highscore           = Int(Highscore1)
}

Upvotes: 1

Related Questions