它应该是当我的玩家达到新的高分时,它会在GameOver场景中显示它,但在这种情况下,它没有这样做。我将所有NSUserDefaults放在一个单独的.swift文件中。
这是我的代码:
import Foundation
class GameState {
var score: Int
var highScore: Int
var stars: Int
class var sharedInstance :GameState {
struct Singleton {
static let instance = GameState()
}
return Singleton.instance
}
init() {
// Init
score = 0
highScore = 0
stars = 0
// Load game state
let defaults = NSUserDefaults.standardUserDefaults()
highScore = defaults.integerForKey("highScore")
stars = defaults.integerForKey("stars")
}
func saveState() {
// Update highScore if the current score is greater
highScore = max(score, highScore)
// Store in user defaults
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(highScore, forKey: "highScoreLabel")
defaults.setInteger(stars, forKey: "stars")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
在我的GameOver场景中,我设置了所有文本标签:
lblHighScore.text = String(format: "High Score: %d", GameState.sharedInstance.highScore)
在我的GameScene中,我拥有它,以便在游戏结束时 同步:
func endGame() {
gameOver = true
GameState.sharedInstance.saveState() //right here
print("saved score")
let reveal = SKTransition.fadeWithDuration(0.5)
let gameScene = GameOver(size: self.scene!.size)
view!.presentScene(gameScene, transition: reveal)
print("new scene")
}
缺少什么?如有必要,将发布更多代码。
答案 0 :(得分:1)
您的编码中存在一个您可能忽略的问题:
您保存为" highScoreLabel"
malloc
但是试着读作" highScore"
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(highScore, forKey: "highScoreLabel")
defaults.setInteger(stars, forKey: "stars")
defaults.synchronize()
在阅读和写入highScore = defaults.integerForKey("highScore")
供将来参考......
我个人在处理密钥时设置静态let变量。所以你以后再也不会遇到这种打嗝。
NSUserDefaults
然后使用
struct Defaults {
static let HighScore = "highScore"
static let Stars = "stars"
}
问题是没有任何变量被更改,代码替换为:
highScore = defaults.integerForKey(Defaults.HighScore)