Reputation: 954
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.
Upvotes: 1
Views: 421
Reputation: 59536
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:
I think you can follow a similar approach with your CCScene subclass.
Upvotes: 0
Reputation: 64477
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;
}
}
Upvotes: 2