Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
Piero Avatar asked Jan 17 '23 01:01

Piero


2 Answers

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

like image 164
Kreiri Avatar answered Jan 18 '23 23:01

Kreiri


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.

like image 45
Jonathan Avatar answered Jan 19 '23 00:01

Jonathan