cocos2d-x HelloWorld プロジェクトでは、別のレイヤーをシーンに追加し、このレイヤーへの参照をデータ メンバーに保持しようとしています。関数HelloWorld::scene()
は静的であるため、この関数内にレイヤーを追加することはできません (レイヤーのデータ メンバーを設定できないため)。
init()
そこで以下のように関数でシーンを取得してみましたが、これはscene = 0x00000000
.
私は何を間違っていますか?
bool HelloWorld::init()
{
bool bRet = false;
do
{
CC_BREAK_IF(! CCLayer::init());
CCScene* scene = NULL;
scene = CCDirector::sharedDirector()->getRunningScene();
// add another layer
HelloWorldHud* layerHud = HelloWorldHud::create();
CC_BREAK_IF(! layerHud);
// set data member
this->layerHud = layerHud;
// next line crashes (because scene is 0x00000000)
scene->addChild(layerHud);
bRet = true;
} while (0);
return bRet;
}
PS: 現在のレイヤーではなくシーンに hud レイヤーを追加したい理由は、現在のレイヤーを移動していて、hud レイヤーを一緒に移動させたくないためです。
編集:受け入れられた回答では複数のオプションが許可されていたため、問題を解決するために私がしたことは次のとおりです。
1.) init() 関数から HUD レイヤーを削除:
bool HelloWorld::init()
{
bool bRet = false;
do
{
CC_BREAK_IF(! CCLayer::init());
bRet = true;
} while (0);
return bRet;
}
2.) 代わりに HUD レイヤーをシーン関数に追加しました (これは cocos2d-iphone で行われた方法でもあります):
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
// scene
scene = CCScene::create();
CC_BREAK_IF(! scene);
// HelloWorld layer
HelloWorld *layer = HelloWorld::create();
CC_BREAK_IF(! layer);
scene->addChild(layer);
// HUD layer
HelloWorldHud* layerHud = HelloWorldHud::create();
CC_BREAK_IF(! layerHud);
scene->addChild(layerHud);
// set data member
layer->layerHud = layerHud;
} while (0);
// return the scene
return scene;
}
本質的に問題は、「関数は静的なので、この関数内にレイヤーを追加することはできません(レイヤーのデータメンバーを設定できないため)」という私の仮定HelloWorld::scene()
が間違っていた.