使用NotificationCenter在同场景的不同层之间传输数据:
1.在第一个层里添加发送消息的函数
bool HelloWorld::init()
{
scheduleOnce(schedule_selector(HelloWorld::sendMsg), 3.0f);
//在3秒后调用sendMsg函数
return true;
}
void HelloWorld::sendMsg(float dt){
String* s = String::create("World");
//使用cocos2d::String储存要传输的数据
NotificationCenter::getInstance()->postNotification("Hello", s);
//发送消息,消息名称为"Hello",内容为定义好的s
}
2.在第二个层里接受消息
bool GameScene::init(){
NotificationCenter::getInstance()->
addObserver(this, callfuncO_selector(GameScene::Hello), "Hello", NULL);
//检测名为"Hello"的消息,如果接收到,则调用函数Hello
return true;
}
void GameScene::Hello(Ref* pData){
String* s = (String*)pData;
//将参数转化为需要的类型并存储
log("%s", s->getCString());
//打印接收到的参数
}
这个方法还是很方便好用的。