There are three messageboxes in the current scene, here I named them _grannyMessage, _grannyMessage2, _grannyMessage3 respectively. I want to make _grannyMessage disappear from the scene when _grannyMessage3 is created in the scene. I am trying to use the "this->removeChild(_grannyMessage);" function but it seems it's not working, am I calling the wrong function anyway? Thanks a lot
auto grannyListener = EventListenerTouchOneByOne::create();
grannyListener -> setSwallowTouches(true);
grannyListener -> onTouchBegan =[this](Touch *touch, Event *event){
MessageBoxes *_grannyMessage =
MessageBoxes::create("The hen can lay an egg everyday");
if(i==0){
_grannyMessage->setPosition(Vec2(600, 450));
addChild(_grannyMessage);
}
else if (i==1)
{
MessageBoxes *_grannyMessage2 =
MessageBoxes::create("2 yuan, that's all I can offer you for the hen");
_grannyMessage2->setPosition(Vec2(400, 450));
addChild(_grannyMessage2);
}
else if (i==2)
{
this->removeChild(_grannyMessage);
MessageBoxes *_grannyMessage3 =
MessageBoxes::create("Well");
_grannyMessage3->setPosition(Vec2(800, 450));
addChild(_grannyMessage3);
}
else
{
return false;
}
i++;
return false;
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(grannyListener, this);
It doesn't work because you create new
_grannyMessage
every time the user touches the screen and only the first one is added to the scene. Then with the third one you try to remove a child that is not on the screen (because it was just created, at the begining of the touch handler).This happens because when the method ends, the
_grannyMessage
variable goes out of scope and is forgotten (the first one is retained though, as you added it to the scene).To solve your problem, you need to store the first
_grannyMessage
, for example like this :In
*.h
of your class add something like this inside your class :private MessageBoxes *_grannyMessage;
Then change your touch handler to this :