Search code examples
sprite-kitskscene

mutableDictionary doesn´t transfer objects to next scene in sprite kit


i know there are a few different topics about that and i read all of them but my first skscene won´t transfer my dictionary objects to the next scene.

the first looks like: (touchesBegan) menuScene

HelloScene *gameScene1 = [HelloScene sceneWithSize:self.size];
self.userData = [NSMutableDictionary dictionary];
[self.userData setValue:@"1" forKey:@"selectBall"];
[gameScene1.userData setObject:[self.userData objectForKey:@"selectBall"] forKey:@"selectBall"];
[self.view presentScene: gameScene1];

and scene two: (initWithSize) gameScene1

int setBall = [[self.userData objectForKey:@"selectBall"] intValue];
self.selectBall = setBall;

Solution

  • As LearnCocos2D already mentioned in the comments, you can't access the userData of the first scene in the second scene. So you will have to set the userData to the new scene before opening it:

    - (void) showNewScene {
          SKView *currentView = (SKView *) self.view;
          SKScene *currentScene = [currentView scene];
          HelloScene *gameScene1 = [HelloScene scene];
          [gameScene1.userData setObject:[currentScene.userData objectForKey:@"1"] forKey:@"selectBall"];
          [currentView presentScene:gameScene1];
    
     }
    

    Then, you can access the userData in the new loaded gameScene1 with the objectForKey-method.

    Also you could use NSUserDefaults to save it. The nice part about using that is, that you can use the information everywhere in your app:

    NSString *valueToSave = @"1";
    [[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"selectBall"];
    

    If you want to get it back, just call your userdefaults again:

    NSString *savedValue = [[NSUserDefaults standardUserDefaults]
        stringForKey:@"selectBall"];