最近在学习cocos2dx需要在场景切换的时候传值这方面的资料貌似很少。大都都有错误.
应用场景是: A->B B->A在B退回A时并传递参数
首先在B头文件定义
std::function<void(int a)> func;
std::function<void(__String * userName, __String * passWord )> funcU;在 A中声明并实现
void callback1(int a);
void callback2(__String *userName,__String *password);
void LoginLayer::callback1(int a)
{
log("反向传值 %d",a);
}
void LoginLayer::callback2(__String *userName,__String *password){
log("userName = %s \n password = %s ",userName->getCString(),password->getCString());
}在A->B时 注册回调函数
auto rScene = ResigisterLayer::createScene();
ResigisterLayer *resigisterLayer = dynamic_cast<ResigisterLayer*>(rScene->getChildByTag(1));
IF_NULLPTR_LOG_ASSERT_RETURN(resigisterLayer);
resigisterLayer->func = std::bind(&LoginLayer::callback1,this,std::placeholders::_1 );//绑定回调函数到子场景
resigisterLayer->funcU = std::bind(&LoginLayer::callback2, this,std::placeholders::_1,placeholders::_1);
Director::getInstance()->pushScene(rScene);
在B场景中调用场景中调用func(99);就相当于调用的主场景的callback1(99)了。相当于调用的主场景的callback1(98)了。
本文介绍如何在Cocos2d-x的游戏开发中实现场景间的参数传递,特别是从子场景向主场景回传参数的具体实现方法。通过使用`std::function`和`std::bind`来绑定回调函数。
1万+

被折叠的 条评论
为什么被折叠?



