I'm making some great progress with my first iOS game app, currently I'm working on the high score element and if anyone would be so kind as to help guide me how to use the correct code.
I've followed a few tutorials with mixed results, so far I'm increasing the score count by 1 for each screen press (will be changed but using for the purpose for this post), this works fine however I need some help saving both the high score using NSUserDefaults
and also displaying the high score.
Below is the extract of my code, currently the score works fine however the high score remains at 0 and doesn't increase. Any help would be appreciated!
Here is my code.....
Thank you.
EDITED WITH REWORKED CODE
// in gameScene:
var scoreLabelNode = SKLabelNode()
var score = NSInteger()
var highScoreLabelNode = SKLabelNode()
var highScore = NSInteger()
// in did move to view
score = 0
scoreLabelNode.fontName = "Helvetica-Bold"
scoreLabelNode.position = CGPoint(x: self.frame.size.width / 2.8, y: self.frame.size.height / 1.2 )
scoreLabelNode.fontSize = 20
scoreLabelNode.alpha = 0.2
scoreLabelNode.zPosition = -30
scoreLabelNode.text = "Score \(score)"
self.addChild(scoreLabelNode)
// start of high score
var highScoreDefault = NSUserDefaults.standardUserDefaults()
if (highScoreDefault.valueForKey("highScore") != nil){
highScore = highScoreDefault.valueForKey("highscore") as! NSInteger!
highScoreLabelNode.text = NSString(format: "highscore : %i", highScore) as String
}
// highScore = 0
// if (score > highScore) {
// highScore = score
// highScoreLabelNode.text = NSString(format: "highscore : %i", highScore) as String
// }
highScoreLabelNode.fontName = "Helvetica-Bold"
highScoreLabelNode.position = CGPoint(x: self.frame.size.width / 2.6, y: self.frame.size.height / 1.3 )
highScoreLabelNode.fontSize = 20
highScoreLabelNode.alpha = 0.2
highScoreLabelNode.zPosition = -30
highScoreLabelNode.text = "High Score \(score)"
self.addChild(highScoreLabelNode)
// in touches began
let incrementScore = SKAction.runBlock ({
++self.score
self.scoreLabelNode.text = "Score \(self.score)"
})
self.runAction(incrementScore)
// in update before each frame
// highScore = 0
if (score > highScore) {
highScore = score
highScoreLabelNode.text = NSString(format: "highscore : %i", highScore) as String
}