首页 > 解决方案 > 如何在 Spritekit 和 Swift 5 中保存分数

问题描述

我查看了整个互联网,以了解如何使用 NSUserDefaults 保存分数。他们都没有最终工作。可能它们都来自 Swift 3。我希望弄清楚如何在 Swift 5 和 Spritekit 中做到这一点。我正在制作一款名为 Plane Dash 的 Flappy Bird 游戏,我想保存分数并最终添加高分功能。

到目前为止 我已经尝试过:到目前为止我尝试过的代码。

标签: swiftswift5

解决方案


您可以使用 UserDefualts。例如

    var score = 0
    //SET
    UserDefaults.standard.set(score, forKey: "score")
    //RETRIVE
    score = UserDefaults.standard.integer(forKey: "score")

编辑:

var currentScore = 100 //change that to the players current score.
let highScore  = UserDefaults.standard.integer(forKey: "highScore") //Get the users high score from last time.

if(currentScore > highScore){// check and see if currentScore is greater than highScore.

    UserDefaults.standard.set(currentScore, forKey: "highScore")//if currentScore is greater than highScore, set it in UserDefualts.

}

编辑 Pt.2

labelName.text! = "\(highScore)"

推荐阅读