Susitha
Susitha

Reputation: 3349

How to pass parameters between cocos2d scenes

I am using

[[CCDirector sharedDirector] replaceScene:[CCTransitionCrossFade transitionWithDuration:0.5f scene:[CCBReader sceneWithNodeGraphFromFile:@"SongLoadingScene.ccbi"] ]];

For transition scene by scene. How to pass parameters to a scene.

Upvotes: 0

Views: 1590

Answers (4)

AKM
AKM

Reputation: 568

The secret lies in:

[CCBReader loadAsScene:@"YourCustomCCBFile"]

It creates a CCScene and adds your custom file as it's child. If you want to access your custom object you can do this this way:

CCScene *scene = [CCBReader loadAsScene:@"YourCustomCCBFile"];
CustomClass *customObject = [[scene children] firstObject];
customObject.property = @"hi";

[[CCDirector sharedDirector] replaceScene:scene];

Just remember, that if you set some property this way, it will not be available in

- (void)didLoadFromCCB

use instead:

- (void)onEnter

Upvotes: 1

lucianomarisi
lucianomarisi

Reputation: 1552

CCBReader returns a CCScene with whatever you pass as the only child, so you can create a constructor on you CustomScene like this:

@interface CustomScene ()

@property (nonatomic, strong) id customParameter;

@end

@implementation CustomScene

+ (CCScene *)sceneWithCustomParameter:(id)customParameter
{
    CCScene *customSceneParent = [CCBReader loadAsScene:NSStringFromClass([CustomScene class])];
    CustomScene *customScene = [customSceneParent.children firstObject];
    customScene.customParameter = customParameter;
    return customSceneParent;
}

@end

This should be applicable to any custom CCNode (e.g. CCSprite)

Upvotes: 2

Saturn
Saturn

Reputation: 18159

CCBReader's sceneWithNodeGraphFromFile is just a class method that returns a new instance of CCBReader.

So, if you want to pass an integer to it, first modify sceneWithNodeGraphFromFile to receive it, like

+(CCScene*)sceneWithNodeGraphFromFile:(NSString*)file andInteger:(int)integer;

And then modify CCBReader's constructor to also receive it. If currently it looks like

-(id)initWithFile:(NSString*)file;

You'd have

-(id)initWithFile:(NSString*)file andInteger:(int)integer;

Finally you modify sceneWithNodeGraphFromFile to pass the integer to this new constructor.

Upvotes: 1

Abhineet Prasad
Abhineet Prasad

Reputation: 1271

I don't think you can pass parameters to a scene. However, you could try either of the following to overcome your problem.

  1. Use another class, a singleton, and store the value of the parameter in a variable of the singleton. You could read that variable in your main scene.

  2. Save the value in NSUserDefaults and read it in your scene.

Upvotes: 1

Related Questions