Question

I'm trying to figure out the best way to pass a level parameter between Scenes using Spritebuilder and Cocos2D in Xcode.

I'm using the standard code below to transition between scenes.

[[CCDirector sharedDirector] replaceScene:[CCBReader loadAsScene:@"Gameplay"]];

Any help will be much appreciated.

Was it helpful?

Solution

Assuming that the Gameplay.ccb has a GameplayClass assigned as its custom class, and that class has a property named currentLevel, you can access the instance and assign the level as follows:

CCScene* theScene = [CCBReader loadAsScene:@"Gameplay"];
GameplayClass* game = (GameplayClass*)theScene.children.firstObject;
game.currentLevel = 3;

[[CCDirector sharedDirector] replaceScene:theScene];

Note that by the time currentLevel is assigned the GameplayClass will have already run its init and didLoadFromCCB methods since that happens during loadAsScene. If you need further init processing override onEnter in GameplayClass:

-(void) onEnter
{
    [super onEnter]; // must call super

    switch (self.currentLevel)
    {
        // other switches omitted...

        case 3:
            // your level 3 code here
            break;
    }
}

OTHER TIPS

In my game (made with Cocos2d 2.0 + CocosBuilder) I added a class method loadWithLevelID:levelID to the class GameObjectLayer that manages the gameplay elements:

@implementation GameObjectLayer {
    G1LevelID * _levelID;
}
// load a Luminetic Land game object layer
+ (instancetype)loadWithLevelID:(G1LevelID*)levelID {
    NSString * levelFileName = ... builds levelFileName from levelID;
    GameObjectLayer * gol = (GameObjectLayer*) [CCBReader nodeGraphFromFile:levelFileName];
    [gol setLevelID:levelID];
    return gol;
}
- (void)setLevelID:(G1LevelID*)levelID {
    _levelID = levelID;
}

So now I can create a GameObjectLayer typing

GameObjectLayer * gol = [GameObjectLayer loadWithLevelID:levelID];

In general, adding a "load" method to the classes that map ccbi files offers the following benefits:

  1. Only the class knows the name of its related ccbi file.
  2. The ccbi file to create a given class is referenced only once in the entire project.
  3. All the logic to set up an object (e.g. of type G1GameObjectLayer) is inside the object itself.

I think you can follow a similar approach with your CCScene subclass.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top