CC_CALLBACK pass argument

Hi there,

I need to pass a simple int to my method using CC_CALLBACK.

I tried several ways to pass it but I still didnt figure out.

My code is like this:

CC_CALLBACK_1(GameScene::click, this) // I would like to pass id = 1
void GameScene::click(int id){}

CC_CALLBACK_X is actually a shorthand for std::bind, with X being {0, 1, 2, 3}.

All variants take a function and any number of other arguments. The result is a function with X arguments which has the first and the last arguments bound to the second and last arguments of CC_CALLBACK.

Usually, the result of CC_CALLBACK is a function taking X arguments which can be called without an explicit object (because the first argument argument was already bound to this). In your case, the result you need is a function which takes 0 arguments, but has two arguments bound (this and id). For that you need to use CC_CALLBACK_0:

CC_CALLBACK_0(GameScene::click, this, 1)

1 Like

hi @kaizenco

I usually do using a lambda function.
I will give you an example for your reference -

see you must have come across CallFunc in cocos2d-x -

auto cb = CallFunc::create(CC_CALLBACK_0(HelloWorld::myFunction));

so, you are calling the function here. But say for similar example you want to pass an argument to your method while calling.

Alternate Way

you are making a callback like this -

auto cb = CallFunc::create( [&] () { 
    // your function definition here
});

no need for declaring, calling - just define directly also it can access all global and local variables and alter them.

Say for instance -

void TestFunc(int x)
{
    auto cb = [&, x] () {
        // your function logic
};
// call the lambda function here
cb();
}

now any global variables will be accessed by reference when you specify [&] and if you want to access variables local to the function you can also access them like this [&, x]

Note:

Lambda functions are new to C++11, but provides great flexibility to your code.
might give a look. They are super awesome. :smile:

Happy Coding. :wink:

1 Like

Hello,

If you want pass parameter using CC_CALLBACK. This link may help you out.

Thanks