-1

I"m trying to get a high score to save each time the player exits the app, but I'm struggling to get it to work and I'm confused as to where I'm making a mistake.

var gameSettings = Settings.sharedInstance
let HIGHSCORE = "HIGHSCORE"

if gameSettings.highScore < score{
        gameSettings.highScore = score

        UserDefaults.standard.set(gameSettings.highScore, forKey: HIGHSCORE)
    }

        if gameSettings.highScore >= score{
            gameSettings.score = score

    }

    let gameOverHighScore = SKLabelNode()
    gameOverHighScore.name = "gameOverHighScore"
    gameOverHighScore.fontName = "Helvetica Neue UltraLight"
    if let HIGHSCORE = UserDefaults.standard.value(forKey: HIGHSCORE) {
        gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M"
    }
    gameOverHighScore.fontColor = SKColor.white
    gameOverHighScore.position = CGPoint(x: 0, y: -175)
    gameOverHighScore.fontSize = 70
    gameOverHighScore.zPosition = 52
    addChild(gameOverHighScore)
ahuddle9
  • 3
  • 1

2 Answers2

0

Here is a simple example on how to do it:

let firebaseId = user.uid // Variable we want to save
UserDefaults.standard.set(firebase, forKey: "firebase") // Saving the variable with key "firebase"

And now to retrieve:

if let firebaseId = UserDefaults.standard.string(forKey: "firebase") {
    print("Firebase ID: \(firebase)")
}

On your code, you are retrieving to HIGHSCORE, and you should be retrieving to something like gameSettings.highScore (Based on what I can infer from your code)

Mago Nicolas Palacios
  • 2,501
  • 1
  • 15
  • 27
0

In if let HIGHSCORE = UserDefaults.standard.value(forKey: HIGHSCORE) { gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M" }

you are try find value in UserDefaults not by key HIGHSCORE, but by new value HIGHSCORE of type ANY. If you want to fix it, you can do like this:

if let HIGHSCORE = UserDefaults.standard.value(forKey: self. self.HIGHSCORE) as! Int { gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M" }

or you can unwrap value in new value with another name. And don't forget to cast value to appropriate type or use

UserDefaults.standard.integer(forKey: self.HIGHSCORE)
D. Pass
  • 83
  • 9