[Cocos2d-x] How to send object from Scene to Scene via Notification Center or EventCustom

[Cocos2d-x] How to send object from Scene to Scene via Notification Center or EventCustom
0

Dear all,

I am trying to send the object of SIOClient from one scene to other scene. After implemented the code below, I emit an event at HelloWorld side but I got the bad access error at _sioClient in HelloWorld.

Am I did something wrong below? Please HELP!!!

First Scene

// SIO connect
_sioClient = SocketIO::connect( "25.0.126.193:3000", *this); //223.16.193.48 25.0.126.193
    
// Send sioClient to NC
PostMessage(_sioClient);

void AppDelegate::PostMessage(cocos2d::Ref* pSender)
{
    __NotificationCenter::getInstance()->postNotification("getSIOClient", _sioClient);
}

Second Scene

// Get SIOClient from Notification Center
__NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(HelloWorld::getMessage), "getSIOClient", NULL);


void HelloWorld::getMessage(cocos2d::Ref* pSender)
{
    _sioClient = (SIOClient*)pSender;
}

Dear all,

I also tried to use EventCustom as below:
First Scene

// Create Event getSIOClient (EventCustom)
    _sioClient = SocketIO::connect("25.0.126.193:3000", *this);
    EventCustom event("getSIOClient");
    event.setUserData((void*)_sioClient);
    EventDispatcher* _eventDispatcher = Director::getInstance()->getEventDispatcher();
    _eventDispatcher->dispatchEvent(&event);

Second Scene

// Get SIOClient from EventCustom
    auto _eventListener = EventListenerCustom::create("getSIOClient", CC_CALLBACK_1(Table::getSIOClient, this));
    EventDispatcher *_eventDispatcher = Director::getInstance()->getEventDispatcher();
    _eventDispatcher->addEventListenerWithSceneGraphPriority(_eventListener, this);

void Table::getSIOClient(cocos2d::EventCustom* event)
{
    _sioClient = ((cocos2d::network::SIOClient*)event->getUserData()); 
}

I also got the same bad access error as Notification Center:

Please help :pray:

This is where a singleton helper class that maintains the SIOClient would be a good practice and what I would recommend. Instead of passing it around, having it inside a singleton instance that can be accessed from any other instances.

3 Likes

Thanks for the help.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.