Reputation: 121
Apologize if this is a beginner question, but I am having trouble finding a solution online. Most of the help I could find did not solve my problem and were for a previous version of Swift.
I would like to keep a cumulate score of a player in a game. It would be zero the first time they logged in, but everytime they played it would increase depending on how many rounds they played.
I've tried a few arrangements, but right now in my AppDelegate file I have:
UserDefaults.standard.set(Int(100),forKey:"TotalPoints")
Then, in other parts of the GameScene when the player advances I have:
let defaults=UserDefaults.standard
var CurrentExtras=defaults.integer(forKey: "TotalPoints")
CurrentExtras = CurrentExtras+100
UserDefaults.standard.set(Int(CurrentExtras),forKey:"TotalPoints")
This works for in game updating, but once I close the app and reboot it, then it goes back to the initial value. How do I check the initial Defaults to make sure it is not overwriting one? Am I doing this correct to begin with?
Upvotes: 0
Views: 344
Reputation: 1482
If you are setting the default value in the AppDelegate you are setting that value back to 100 every time the app launches.
Try replacing:
UserDefaults.standard.set(Int(100),forKey:"TotalPoints")
to:
if UserDefaults.standard.value(forKey: "TotalPoints") == nil {
UserDefaults.standard.set(100, forKey: "TotalPoints")
}
or:
UserDefaults.standard.register(defaults: ["TotalPoints" : 100])
That way it will only set the key TotalPoints to 100 the very first time the app launches.
Upvotes: 3