Cocos2d-x中,使用NotificationCenter在Layer之间传输数据

本文介绍如何利用NotificationCenter在Cocos2d-x游戏引擎中实现不同层之间的数据传输,通过发送和接收消息的方式,使得层与层之间能够进行高效的数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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());
	//打印接收到的参数
}
这个方法还是很方便好用的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值