Piero
Piero

Reputation: 9273

how push scene in cocos2d and pass parameters

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?

Upvotes: 4

Views: 3057

Answers (4)

Olie
Olie

Reputation: 24685

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;

Upvotes: 0

Jonathan
Jonathan

Reputation: 3034

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.

Upvotes: 4

Kreiri
Kreiri

Reputation: 7850

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

Upvotes: 5

brigadir
brigadir

Reputation: 6942

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.

Upvotes: 0

Related Questions