Search code examples
iphoneiosios7sprite-kit

SpriteKit: Passing data between scenes


I am stuck trying to pass data between scenes "SKScene" in SpriteKit. For instance I would like to pass the score from level A to Level B.

Maybe the solution is archiving but I would like to implement something more simpler like the way we use with view controllers.

Any clue in this regard will be very much appreciated.


Solution

  • If you're going to be passing around the score to a lot of different scenes, you might want to store it in NSUserDefaults or some accessible storage mechanism. However, if you're looking to pass data between SpriteKit objects, every SKNode (including SKScene) has a dictionary property called userData that you can use for whatever you so desire. Here's an example of how you might pass the score between scenes:

     - (void)changeScene
     {
          SKView *spriteView = (SKView *) self.view;
          SKScene *currentScene = [spriteView scene];
          SKScene *newScene = [MySceneClass scene];
          [newScene.userData setObject:[currentScene.userData objectForKey:@"score"] forKey:@"score"];
          [spriteView presentScene:newScene];
    
     }