0

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.

dancingbush
  • 2,131
  • 5
  • 30
  • 66
  • Well then move your initWithSize code to a "postInit" function or so, and then assign the property, then call that function. – CodeSmile Dec 02 '14 at 10:51
  • U mean call a separate init function when initialising the scene object? Or a call a separate function after tej object is initialised? – dancingbush Dec 02 '14 at 11:18

1 Answers1

1

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.

Mobile Ben
  • 7,121
  • 1
  • 27
  • 43
  • Thanks but I'm not sure how I would implement this, is there documentation or basic example u can recommend, – dancingbush Dec 03 '14 at 11:49
  • This depends on how you want to do it. If you do it via global, I think that should be obvious, just assign the global with something like `g_GameState = [[GameState alloc] init]` early on. If you are going to use a singleton, you can see an example here: http://stackoverflow.com/questions/7568935/how-do-i-implement-an-objective-c-singleton-that-is-compatible-with-arc – Mobile Ben Dec 04 '14 at 09:32