0

Im trying to pass my Score from GameScene to GameOverScene. I just want to set the text of the label in the GameOverScene with my variable Score that I passed to it. I am using this:

SKView *spriteView = (SKView *) self.view;
    SKScene *currentScene = [spriteView scene];
    GameOverScene *gameOverScene = [GameOverScene sceneWithSize:self.frame.size];
    [gameOverScene.userData setObject:[currentScene.userData objectForKey:@"score"] forKey:@"score"];
    [self.view presentScene:gameOverScene transition:[SKTransition doorsCloseHorizontalWithDuration:1]]; // animation

How do I access the score variable now in my GameOverScene?

Thanks for any answers.

EDIT:

Okay I have a variable int Score; . How do I connect the objectForKey@"score" to this variable?

EDIT2:

[score setText:[NSString stringWithFormat:@"Score: %@", [self.userData valueForKey:@"score"]]];

With that I get Score: (null)

Bhanu
  • 1,211
  • 9
  • 17

1 Answers1

0

First you need to initialize userData for GameScene in didMoveToView:

self.userData = [NSMutableDictionary dictionary];

After that, if you want to save your integer score, add:

score = 100;    // assume your score is 100 now
[self.userData setObject:[NSString stringWithFormat:@"%d", score] forKey:@"score"];

Right before presenting the next scene, edit the code you posted in the question like this:

SKView *spriteView = (SKView *)self.view;
SKScene *currentScene = [spriteView scene];
GameOverScene *gameOverScene = [GameOverScene sceneWithSize:self.frame.size];

// Initialize userData for the next scene
gameOverScene.userData = [NSMutableDictionary dictionary];
[gameOverScene.userData setObject:[currentScene.userData objectForKey:@"score"] forKey:@"score"];
NSLog(@"GameScene score: %lu", [[currentScene.userData objectForKey:@"score"] integerValue]);

[self.view presentScene:gameOverScene transition:[SKTransition doorsCloseHorizontalWithDuration:1]];

Now you should see your new scene and check the score wherever needed:

int score = [[self.userData objectForKey:@"score"] intValue];
NSLog(@"GameOverScene score: %d", score);
WangYudong
  • 4,107
  • 3
  • 27
  • 51