我在使用Swift在我的xcode游戏中将货币实现为UserDefault时遇到了困难。随着回合的进行,我的货币将会计入,但是当回合结束时(游戏结束),我的累积货币将被设置回零。这是我目前的进展:
这是我的货币变量:
var currency = 0 {
didSet {
currencyLabel.text = "ATTESTER: " + UserDefaults().integer(forKey: "currency").description
}
}
这是我保存货币的功能
func saveCurrency(value:Int){
UserDefaults.standard.set(value, forKey: "currency")
UserDefaults.standard.synchronize()
}
这是我加载货币的功能
func loadCurrency()-> Int{
return Int(UserDefaults.standard.integer(forKey: "currency"))
}
这是我的didBegin(联系人)设置。联系部分可以添加货币,但它似乎无法保存。
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.node?.name == "Attest" ||
contact.bodyB.node?.name == "Attest" {
if contact.bodyA.node == player {
contact.bodyB.node? .removeFromParent()
} else {
contact.bodyA.node? .removeFromParent()
}
currency += 1
saveCurrency(value: Int)
return
}
我创建货币标签[编辑1]
的功能 func createCurrency() {
currencyLabel = SKLabelNode(fontNamed: "Optima-ExtraBlack")
currencyLabel.fontSize = 24
currencyLabel.position = CGPoint(x: frame.minX + 20, y: frame.maxY - 40)
currencyLabel.horizontalAlignmentMode = .left
currencyLabel.text = "ATTESTER: 0"
currencyLabel.fontColor = UIColor.black
addChild(currencyLabel)
}
这里的任何人都可以为我提供一些新的想法,我可以做些什么来解决这个问题,我一直试图解决它几个小时,但我似乎无法弄明白。谢谢:))