I want to change Create function for avoiding the Global variable usage. I want to pass my values (e.g scores) while Calling and creating other scenes. One method i found is the use of Global variable in create Function but i want to use those values without using global variables. Please reply me fast , i'm new in cocos2d-x. and also tell me if there is any other method.
i personally use these two approaches ... so choose which fits you the most!
take for example this ScoreScene class and how its created.
1)- approach one
class ScoreScene : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene(bool won, int score) {
auto scene = Scene::create();
auto layer = ScoreScene::create(won, score);
scene->addChild(layer);
return scene;
}
static ScoreScene* create(bool won, int score) {
ScoreScene *layer = new(std::nothrow) ScoreScene;
if (layer)
{
layer->isWinner = won;
layer->m_score = score;
if (layer->init())
{
layer->autorelease();
return layer;
}
}
CC_SAFE_DELETE(layer);
return nullptr;
}
bool init() override {
if(!layer->init()) return;
// initialization code here
return true;
}
private:
// your properties
int m_score;
bool isWinner;
};
1)- approach two (personally preferred)
make just one method which is createScene instead of two.
class ScoreScene : public cocos2d::Layer
{
public:
cocos2d::Scene* ScoreScene::createScene(bool won, int score)
{
ScoreScene *layer = new(std::nothrow) ScoreScene;
if (layer)
{
layer->isWinner = won;
layer->m_score = score;
if (layer->init())
{
auto scene = Scene::create();
layer->autorelease();
scene->addChild(layer);
return scene;
}
}
CC_SAFE_DELETE(layer);
return nullptr;
}
bool init() override {
if(!layer->init()) return;
// initialization code here
return true;
}
private:
// your properties
int m_score;
bool isWinner;
};