viktorm viktorm - 4 months ago 18
iOS Question

How to request data from another scene in SpriteKit

I have 2

SKScenes
. The first scene has 2 buttons: a male player button and a female player button. The second scene has 2 hidden images: a male player image and a female player images.

If male player is selected in
Scene1
, I want to make the male player image visible in
Scene2
, but I'm having trouble passing the data between
SKScene
s. I'm using Sprite Kit and programming in Swift. Please advise.

Here is what I have tried so far:

// Scene1:

import SpriteKit

class Scene1: SKScene {

var malePlayer = SKSpriteNode()
var femalePlayer = SKSpriteNode()

var maleSelect = false
var femaleSelect = false

// in touches began..
if self.nodeAtPoint(location) == self.malePlayer {
maleSelect = true
// then i present scene2

} else if self.nodeAtPoint(location) == self.femalePlayer {
femaleSelect = true
//then i present scene2



// in scene 2:
class Scene2: SKScene {
var playerSelected: Scene1()
// did move to view
var boy = SKSpriteNode()
var girl = SKSpriteNode()

if self.playerSelected.maleSelect == true {
self.addChild(boy)
} else if self.playerSelected.femaleSelect == true {
self.addChild(girl)
}

Answer

There are several ways to do this. Here is one example that uses NSUserDefaults. One reason that makes this a good option is that the selection will persist even after the app is closed and can be reloaded when the app is next opened.

To save the selection, use the following code:

    if self.nodeAtPoint(location) == self.malePlayer {

        //save the selection in NSUserDefaults
        NSUserDefaults.standardUserDefaults().setBool(true, forKey:"maleSelected")

        //present next scene

    } else if self.nodeAtPoint(location) == self.femalePlayer {

        //save the selection
        NSUserDefaults.standardUserDefaults().setBool(false, forKey:"maleSelected")

        //present next scene
    }

The value is now saved in local storage. When you need to access the selection in your other scenes, grab the value from NSUserDefaults:

So Scene2 might looking something like this:

class Scene2: SKScene {
var playerSelected: Scene1()

// did move to view
var boy = SKSpriteNode()
var girl = SKSpriteNode()

//grab the selection value
let maleSelected = NSUserDefaults.standardUserDefaults().boolForKey("maleSelected")

if maleSelected == true {
self.addChild(boy)
} else {
self.addChild(girl)
}
}
Comments