How do I transfer the user's score to another scene in Swift and SpriteKit?

こ雲淡風輕ζ 提交于 2019-12-18 09:26:04

问题


I have three scenes, a MainMenu Scene, A GamePlay Scene, and a GameOver Scene. The user gets its score in the gameplay scene, and I'm wanting to transfer that score over to the GameOver scene. How can I do this? (If you need my code or more information, just ask!)


回答1:


You can use NSUserDefaults class as an easiest solution...

In your GameplayScene you set score into persistent storage.

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(score, forKey: "scoreKey")

defaults.synchronize()

Later in GameOver scene, you read persistent storage like this:

let defaults = NSUserDefaults.standardUserDefaults()
let score = defaults.integerForKey("scoreKey")
println(score)

About synchronize() method (from the docs):

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

Or I guess you can make a public property (score) on a GameOver scene, and when transitioning, to set that property (from a Gameplay scene) with a current score.

Similarly, you can set a value to userData property which every node has, like this:

 newScene.userData?.setValue(score, forKey: "scoreKey")

EDIT:

NSUserDefaults would be a preferred way if you are interested into a persistence (making a value available between app launches). Otherwise, you can use userData or a struct like pointed by KnightOfDragon in his example.




回答2:


An alternative to NSUserDefaults would be to create a struct that would house all your global data

struct GlobalData
{
  static var gold = 0;
  static var coins = 0;
  static var lives = 0;
}

Then you would just use it like this:

let score = Global.score;

and

Global.score += 10;


来源:https://stackoverflow.com/questions/33641348/how-do-i-transfer-the-users-score-to-another-scene-in-swift-and-spritekit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!