How to click a scene in cocos2d and passing options

I want to know if there is a way to push the scene in cocos2d 2.0 and pass some parameter to this moving scene, for example, I know that in order to click on the scene I use this:

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

and this clicks helloworldlayer, i.e. a simple layer:

 // HelloWorldLayer @interface HelloWorldLayer : CCLayer { } // returns a CCScene that contains the HelloWorldLayer as the only child +(CCScene *) scene; @end 

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

How can i do this?

+4
source share
4 answers

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

+5
source

First you will need to create a method to call with this parameter

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, calling

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

Now this may not be enough, if you need a parameter inside your layer, you will need to do the same for the layer. Create an initmethod using the method, and then pass it further to the layer in the sceneWithParam: method.

+4
source

Do this through a global variable or an external object (accessible from the "pusher" and HelloWorldLayer . Or even you can pass the parameter through the userData property HelloWorldLayer .

0
source

Jonathan and Crarey respond well, but could you just add the properties to your pushed scene and set them? Thus, the code will look something like this (typing in a browser, you may need to configure it):

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

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

 @property (strong, nonatomic) NSString *param1; @property (readwrite) BOOL *param2; @property (strong, nonatomic) NSNumber *param3; 
0
source

All Articles