How do I increment and save a int value in Swift?

1.5k views Asked by At

Im trying to keep track of how many times the user loses in my game. So for every loss it goes up by 1. I also want to save it too so the user could see how many total times they lost. Right now the code I have it works the first time and goes to one but if I lose in the game after that it just stays at 1. What am I doing wrong? Thanks!

 class level1: SKScene, SKPhysicsContactDelegate, GKGameCenterControllerDelegate {

      var deathScore = 0


      override func didMoveToView(view: SKView) {

      var deathLabel = SKLabelNode()

      deathLabel = SKLabelNode(fontNamed: "LadyIce-3D")
      deathLabel.text = "100"
      deathLabel.zPosition = 14
      deathLabel.fontSize = 100
      deathLabel.fontColor = SKColor.darkTextColor()
      deathLabel.position = CGPointMake(self.size.width / 1.1, self.size.height / 1.4)
      deathLabel.hidden = true
      self.addChild(deathLabel)

      }



  if firstBody.categoryBitMask == HeroCategory && fourthBody.categoryBitMask == GameOverCategory {


    deathScore++
    deathLabel.hidden = false

        let defaults = NSUserDefaults()

        let saveDeaths = NSUserDefaults().integerForKey("saveNumberOfDeaths")
        if(deathScore > saveDeaths)
        {
            NSUserDefaults().setInteger(saveDeaths, forKey: "saveNumberOfDeaths")
        }
        var showNumberOfDeaths = defaults.integerForKey("saveNumberOfDeaths")




    deathLabel.text = String(showNumberOfDeaths)

     }

     }
1

There are 1 answers

11
Leo Dabus On BEST ANSWER

You are declaring a new var deathScore everytime, initialized with 0 and incrementing it. It will always be 1.

UserDefaults.standard.set(UserDefaults.standard.integer(forKey: "saveNumberOfDeaths")+1, forKey: "saveNumberOfDeaths")

deathLabel.text = String(UserDefaults.standard.integer(forKey: "saveNumberOfDeaths"))