CCLayer delete itself

CCLayer delete itself
0.0 0



I’m new to cocos2d-x and c++, I’ve been diving in and so far really like the language and framework. I have a question regarding a layer deleting itself.

My game has several popup dialogues wich inherit from a Dialogue class (which inherits from CCLayer). The dialogue class has a MenuItem in the top right that lets users close the dialogue. It would be neat (in both senses of the word) for the dialogue to be able to remove itself. I tried performing a function call that contains delete this; however it appears the layer still has a pointer to it. What is the best solution to achieve this? I could keep the dialogue around and change the opacity but this seems a bit messy.


There are multiple ways to do it.

You can simply release the cocos2d object when dialogue is closed. In case, if you like to reuse the dialogues in future you can recreate it. Node~~>release;
If your game contains dialouge just With the text then you can hide the dialogue by calling property setVisible. Change the text and show it back.
The third way to release the object is auto release. You can do this with any CCNode. I.e. dialogue~~>autorelease();
But the problem with autorelease approach is when device gets memory warning and your dialogue box is not in use then system will purge it. Later on if you try to use the same object the game will crash. So while using the auto release object you need to always check whether it is NULL

The fourth way is calling object->removefromparent(); with cleanup = yes.

Changing opacity will not release the object though it will hide it from the screen, which can achieved by using set visible property or set position property too.


Many thanks for the quick and detailed response Paras. object->removefromparent(); with cleanup = yes does what I need to do.


In your dialogue close method call this function



@codesnooker @alexvmvm guys I have tried to call removeFromParent but I have got a crash. Please see this thread: [BUG]ui::Button Can't delete it self! This thread was not created by me, seems this is a bug. Did I do something wrong there? What version of cocos2d-x do you use?