Search code examples
swiftswift3userdefaults

How to save a highscore to a game in swift with UserDefaults?


So far this is what I have done, but my high score does not change.

Im leaving out all irrelevant variable etc

If someone could help me that would be fantastic. I have been trying to do this for like 2 days lol help

class GameScene: SKScene, SKPhysicsContactDelegate {

    var score = Int()

    let scoreLabel = SKLabelNode()

    var highScoreLabel = SKLabelNode()

    var highScore = UserDefaults().integer(forKey: "HIGHSCORE")


    func createScene(){



        self.physicsWorld.contactDelegate = self

        scoreLabel.position = CGPoint(x: self.frame.width / 2, y:     self.frame.height / 2 + self.frame.height / 3)
        scoreLabel.text = "\(score)"
        scoreLabel.zPosition = 5
        scoreLabel.fontSize = 60
        scoreLabel.fontColor = UIColor.white
        self.addChild(scoreLabel)

        highScoreLabel.text = "High Score = \(UserDefaults().integer(forKey: "HIGHSCORE"))"
        highScoreLabel.fontColor = UIColor.white
        highScoreLabel.position = CGPoint(x: 120, y: 20)
        addChild(highScoreLabel)

        highScoreLabel.zPosition = 6



    func didBegin(_ contact: SKPhysicsContact) {
        let firstBody = contact.bodyA
        let secondBody = contact.bodyB

        if firstBody.categoryBitMask == physicsCategory.score && secondBody.categoryBitMask == physicsCategory.man{


            score += 1
            scoreLabel.text = "\(score)"
            firstBody.node?.removeFromParent()

            if score < UserDefaults().integer(forKey: "HIGHSCORE") {
                saveHighScore()
            }


        }
        else if firstBody.categoryBitMask == physicsCategory.man && secondBody.categoryBitMask == physicsCategory.score{

            score += 1
            scoreLabel.text = "\(score)"
            secondBody.node?.removeFromParent()

            if score > UserDefaults().integer(forKey: "HIGHSCORE") {
                saveHighScore()
            }

        }


   func saveHighScore() {

        UserDefaults.standard.integer(forKey: "HIGHSCORE")
        highScoreLabel.text = "High Score = \(UserDefaults().integer(forKey: "HIGHSCORE"))"


    }

Solution

  • Try this

    func saveHighScore() {
    UserDefaults.standard.set(score, forKey: "HIGHSCORE")
    }