i am kinda new to swift and i need help with saving an int variable that holds the user's coins that they collect and saving it even after the app closes , so here is what i did , i have two scenes one represents startMenu which has the a struct that has the coins variable ( so i can easily control it from another scene ) , and the other scene which is GameScene , and in GameScene every time the user interacts with a coin node , it adds 1 to the coins variable in StarMenu Scene
here in my struct in StartMenu
struct Variables {
static var CoinsCollected = 0
}
let defaults = UserDefaults.standard
defaults.set(Variables.CoinsCollected, forKey: "CoinsCollected")
defaults.synchronize()
Variables.CoinsCollected += 1
coinsCollectedLabel = SKLabelNode(text: "coins: \(Variables.CoinsCollected)")
You can do this in your Variables
class so your coins are always saved in a persistent file:
class Variables {
static let userDefaults = UserDefaults.standard
struct Constants {
static let CoinsCollectedKey = "CoinsCollected"
}
static var CoinsCollected: Int {
get {
return userDefaults.integer(forKey: self.Constants.CoinsCollectedKey)
}
set(value) {
userDefaults.setValue(value, forKey: self.Constants.CoinsCollectedKey)
}
}
}