-1

每次玩家退出应用程序时,我都会尝试获得高分以保存,但我很难让它发挥作用,而且我很困惑我在哪里犯了错误。

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)
4

2 回答 2

0

这是一个有关如何执行此操作的简单示例:

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

现在要检索:

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

在您的代码中,您正在检索到 HIGHSCORE,并且您应该检索到类似 gameSettings.highScore 的内容(基于我可以从您的代码中推断出的内容)

于 2017-06-20T20:39:35.610 回答
0

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

您尝试在 UserDefaults 中查找值,而不是通过键 HIGHSCORE,而是通过 ANY 类型的新值 HIGHSCORE。如果你想修复它,你可以这样做:

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

或者你可以用另一个名字解开新值中的值。并且不要忘记将值转换为适当的类型或使用

UserDefaults.standard.integer(forKey: self.HIGHSCORE)
于 2017-06-20T20:53:56.660 回答