重启后分数重置

时间:2015-06-26 13:39:43

标签: ios swift

我正在努力制作一个点击游戏。当我重新开始游戏时,它会显示旧的分数,但是当我再次点击时,它会将分数重新设置为0.我认为它是从我的全局变量中提取信息,而不是从我的NSUserdefaults中提取信息,我不知道为什么。

var clickerBTN: UIButton!
var scoreLbl: UILabel!
var Score = NSInteger()
override func didMoveToView(view: SKView) {

    var ScoreDefault = NSUserDefaults.standardUserDefaults()

  if (ScoreDefault.valueForKey("Score") != nil)
        {
        var Score = ScoreDefault.valueForKey("Score") as! NSInteger!
        }
    var Score = ScoreDefault.valueForKey("Score") as! NSInteger!
    ScoreDefault.setValue(Score, forKey: "Score")
    ScoreDefault.synchronize()

    scoreLbl = UILabel(frame: CGRect(x: 0,y: 0,width: 200,height: 90))
    scoreLbl.center = CGPoint(x: view.frame.size.width*0.5, y: view.frame.size.height*0.10)
    scoreLbl.text = NSString(format: "Score : %i", Score) as String
    scoreLbl.textColor = UIColor.blackColor()
    scoreLbl.textAlignment = NSTextAlignment.Center

    let clickerImage = UIImage(named: "PLACEHOLDER")
    clickerBTN = UIButton(frame: CGRect(x: 0, y: 0, width: 350, height: 350))
    clickerBTN.center = CGPoint(x: view.frame.size.width*0.5, y: view.frame.size.height*0.50)
    clickerBTN.addTarget(self, action: Selector("click"), forControlEvents: UIControlEvents.TouchUpInside)
    clickerBTN.setImage(clickerImage, forState: UIControlState.Normal)

    self.view?.addSubview(clickerBTN)
    self.view?.addSubview(scoreLbl)
}

我的点击功能

func click(){

    var ScoreDefault = NSUserDefaults.standardUserDefaults()
    ScoreDefault.setValue(Score, forKey: "Score")
    ScoreDefault.synchronize()
    Score++
    scoreLbl.text = NSString(format: "Score : %i", Score) as String

}

1 个答案:

答案 0 :(得分:0)

我明白了。这只是一个愚蠢的语法错误。当我在“didMoveToView”中调用score时,我必须先删除“var”,因为我在单击按钮时取消了全局变量。