Passing level with SKTransistion issue

25 views Asked by At

When making transition to a new scene, (i am calling a instance of self for the new scene), I am trying to set the level number as a property of the new instance.

Problem is when the instance is first created initWithSize is called before I can set the level property, and i can only set the level property after the instance created, therefore the property level is always set to its default (0) when initWithSize first called.

 MyScene *destinationScene = [[MyScene alloc]init];

    destinationScene.currentLevel = (int) level;

    NSLog(@"519 Level Passed: %d New Level: %d", (int)level, destinationScene.currentLevel);

    SKTransition *transtition = [SKTransition doorwayWithDuration:2];
    [self.view presentScene:destinationScene transition:transtition];

InitWithSize: check for level number here and load

 _currentLevel = self.currentLevel;

        // check if no level ie loading game first  time
        if (_currentLevel==0) {
            _currentLevel=1;
        }

        [self loadLevel:_currentLevel];

Only way around it I have found is to call initWithSize twice which uses up memory and is messy. Any feedback appreciated.

1

There are 1 answers

2
Mobile Ben On BEST ANSWER

You want to decouple your game state from your scenes. Create a class like GameState (add a prefix is appropriate). You have 2 choices here. You can create a global instance of your game state, or a singleton to access the game state.

Something like this (this has a defined singleton class method):

@interface GameState : NSObject

@property (nonatomic, assign) NSInteger currentLevel;

// Add other properties here

+ (instancetype)sharedInstance;

@end

You can then load the level later using something like:

[newScene loadLevel:[GameState sharedInstance].currentLevel];

The benefit of this is that you can now access things like currentLevel as well as any other essential items like score, lives, etc from one common instance.