Question

i want know if there is a way to push a scene in cocos2d 2.0 and pass some parameter to this pushed scene, for example, i know that to push a scene i use this:

[[CCDirector sharedDirector] pushScene:[HelloWorldLayer scene]];

and this push the helloworldlayer, that is a simple layer:

// HelloWorldLayer
@interface HelloWorldLayer : CCLayer
{
}

// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;

@end

but i want pass to this layer some parameter, so when the layer is pushed i can use the parameter i passed.

how i can do it?

Was it helpful?

Solution

you can do something like +(CCScene *) sceneWithParameter:(ParameterType)parameter; instead of +(CCScene *) scene;

OTHER TIPS

First you will have to create a method to call with the parameter like so

HelloWorldLayer.h

@interface HelloWorldLayer : CCLayer
{
}
+(CCScene *)sceneWithParam:(id)parameter;

@end

HelloWorldLayer.m

@implementation HelloWorldLayer

+(CCScene *)sceneWithParam:(id)parameter
{
    [[parameter retain]doSomething];
    CCScene * scene = [CCScene node];
    HelloWorldLayer *layer = [HelloWorldLayer node];
    [scene addChild: layer];
    return scene;
}

-(id) init
{
    if(self = [super init])
    {

    }
    return [super init];
}

// All your methods goes here as usual

@end

Then you push it by calling

[[CCDirector sharedDirector] pushScene:[HelloWorldLayer sceneWithParam:obj]];

Now this might still not be enough, if you need the parameter inside your layer you will need to do the same thing for the layer. Create the initmethod with the method and then pass it further to the layer in the sceneWithParam: method.

Do it through global variable or external object (which is accessible from "pusher" and HelloWorldLayer. Or even you can pass the parameter through userData property of HelloWorldLayer.

Johnathan's and Kreiri's answers work well, but couldn't you also just add properties to your pushed scene and set them? So the code would look something like this (typed in browser, you may have to tweak):

HelloLayer *hello = [HelloLayer scene];
hello.param1 = someValue;
hello.param2 = someOtherValue;
hello.param3 = yetAnotherValue;
[[CCDirector sharedDirector] pushScene: hello];

Of course, in HelloLayer.h, you'd define something like:

@property (strong, nonatomic) NSString *param1;
@property (readwrite) BOOL *param2;
@property (strong, nonatomic) NSNumber *param3;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top