Diego Lucero Diego Lucero - 3 years ago 169
Swift Question

Highscores in swift 3 with spritekit

I am currently trying to implement a highscore mechanic for a game I am working on, but all the tutorials online are using UIKit instead of SpriteKit. I also was wondering whether or not to put the code for score in the GameViewController or gamescene.swift

Answer Source

I'd imagine the place where you're keeping track of the score for that particular "play" of your game is in the scene, so that makes the most sense.

What you really need to decide is how to save the high score. The most basic approach is the us UserDefaults.

So when the game ends you can save the score like this:

let defaults = UserDefaults.standard
defaults.set(100, forKey: "HighScore")

That will set the value for the "HighScore" key to whatever you specify (in the above example 100).

Of course, you'll need to make sure the score is higher than the pervious higher one. You can load in previous high score like this:

if let highScore = defaults.value(forKey: "HighScore") {
  if score > highScore {
    defaults.set(100, forKey: "HighScore")

You can load in the "HighScore" value from anywhere in your app. Be it a view controller or scene.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download