0

I pretty much have the same question as this one. But it doesn't explain how to retrieve the score from the dictionary. I want to pass a float called score to another scene.

I have the following code in my update method:

if (lives == 0) {
    SKScene * nextScene = [[GameOverScene alloc] initWithSize:self.size];

    nextScene.userData = [NSMutableDictionary dictionary];
    NSNumber * scoreForDictionary = [NSNumber numberWithFloat:score];
    [nextScene.userData setObject:scoreForDictionary forKey:@"score"];

    [self.view presentScene:nextScene];
}

I have this code in the other scene:

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        NSNumber * scoreNumber = [self.view.scene.userData objectForKey:@"score"];
        score = [scoreNumber floatValue];

        [self showScore];
    }
    return self;
}

I think this is the way to do it, but it doesn't work. Can you please explain how to pass a float to another scene?

Community
  • 1
  • 1
user2255273
  • 938
  • 1
  • 10
  • 29

1 Answers1

2

Your problem is that you are accessing userData before its set. In your first scene you are calling:

SKScene * nextScene = [[GameOverScene alloc] initWithSize:self.size];

Now your

-(id)initWithSize:(CGSize)size

will be called trying to access userData which has not been set yet. Move your code in your second scene to a later point like - (void)didMoveToView:(SKView *)view

Danilo
  • 3,137
  • 2
  • 16
  • 23