swift - I am trying to save an SKLabelNode which is the highscore label but it doesn't work. Also tried UserDefaults
问题描述
I am trying to save high sore in the form of sklabelnode using UserDefaults but it doesn't work. Every time I close and open the app the highscore is gone.
I have tried UserDefaults.
func afterCollision(){
let highScore = "highScore"
if gameSettings.highScore < score{
gameSettings.highScore = score
let defaults = UserDefaults.standard
defaults.synchronize()
defaults.integer(forKey: highScore)
//I tried using this.
}
I expected the highscore to be saved but it is lost after I restart the app.
解决方案
您的代码不会尝试在 UserDefaults 中保存任何内容。您读取一个值并忽略结果。您需要设置新值。
if gameSettings.highScore < score {
gameSettings.highScore = score
UserDefaults.standard.set(score, forKey: "highScore")
}
当您的应用启动时,您可以加载高分:
gameSettings.highScore = UserDefaults.standard.integer(forKey: "highScore")
推荐阅读
- ios - Paypal Native Checkout SDK 抛出错误 - 在 Swift 5 中“无法加载模块 'PayPalCheckout”
- google-bigquery - 如何禁用 Google Big Query 中的预览功能?
- reactjs - 在 Heroku 上构建 Parcel React 应用程序失败
- ios - AVAudioPlayer 播放断断续续且无限?
- pos - 发布 DUKPT 密钥管理时 TermApp Postillion 上的 PIN 转换错误
- rspec - Rspec使用具有`before_validation`回调的范围验证唯一性
- boolean - 使用 9 位加法器进行 9 位减法
- java - 当我尝试 Blaze Persistence 文档示例时发生 ClassCastException
- c# - 分页问题:返回正文中的总计数和总页数,而不添加到正在获取的其他数据
- mysql - 如何在 golang 中创建 sql.mock 以进行插入查询