Hi.
I am quite new on cocos2dx development and I have been trying to chase an issue I have in my code for two days with no satisfactory results.
The issue is that when I call: this->addChild()
on a CCLayer subclass I have end up with “this” pointer setted to NULL value when the call to addChild finish, and I don´t know why. The code is the following:
I have my own CCLayer subclass in which I try to add a child on his init method:
#include "cocos2d.h"
USING_NS_CC;
namespace MyLayerNS{
class MyLayer: public CCLayer{
private:
CCPoint _position;
CCSize _size;
CCLabelTTF* pLabel;
public:
~MyLayer();
void setPosition(CCPoint position);
void setSize(CCSize size);
virtual bool init();
// implement the static instance
CREATE_FUNC(MyLayer);
};
}
And this are my definitions
#include "MyLayer.h"
USING_NS_CC;
namespace MyLayer{
MyLayer::~MyLayer()
{ }
void MyLayer::setSize(CCSize size)
{
_size.width = size.width;
_size.height = size.height;
}
void MyLayer::setPosition(CCPoint position)
{
_position = ccp(position.x, position.y);
}
bool MyLayer::init(){
bool bRet = false;
do
{
CC_BREAK_IF(!CCLayer::init());
pLabel = CCLabelTTF::create("Some ttf label", "Arial", 24);
CC_BREAK_IF(! pLabel);
pLabel->retain();
CCPoint lp = CCPoint(10, 10);
pLabel->setPosition(lp);
this->addChild(pLabel, 1);
bRet=true;
}while (0);
return true;
}
The issue is on the call to this->addChild(pLabel, 1);
It executes it but jumps straight out of the do while statement with this=NULL
On the HelloWorldScene I have added that new layer on the _scene()_ method:
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
// 'scene' is an autorelease object
scene = CCScene::create();
CC_BREAK_IF(! scene);
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
CC_BREAK_IF(! layer);
// add layer as a child to scene
scene->addChild(layer,-1);
MyLayerNS::MyLayer* someLayer= MyLayerNS::MyLayer::create();
CC_BREAK_IF(!someLayer);
someLayer->retain();
someLayer->setPosition(VisibleRect::leftTop());
someLayer->setSize(CCSize(10,10));
scene->addChild(someLayer,1);
} while (0);
// return the scene
return scene;
}
On that code the MyLayerNS::MyLayer::create()
ends up calling MyLayerNS::MyLayer::init()
where I have the issue.
Any idea how I can solve this problem?
Thanks.