Search code examples
c++cocos2d-iphonecocos2d-x

An object which is accessible by all Scenes in cocos2d-x


I have my own ClientGame class and I want to add an object of this class, which will be accessible by all Scenes in cocos2d-x. I tried following methods, but they don't work.

1) I create a BaseScene class which contains my class object and inherits cocos2d::Layer. Then, every scene inherit this BaseScene. It compiles, but the window screen just show up and turn off right away.

2) I tried to inherit both cocos2d::Layer and BaseScene at the sametime. It compiles, but it produces same result as above.

What is the best way to create an object which is accessible by all Scenes? Here is my code.

BaseScene.h

#include "cocos2d.h"
#include "ClientGame.h"


class BaseScene
{
public:

private: 
  ClientGame mClientGame;

};

ClientGame.h

class ClientGame
{
public:
    ClientGame(void);
    ~ClientGame(void);    
    ClientNetwork* network; 
    void sendActionPackets(int action);
    void sendLineDestroyed();
    char network_data[MAX_PACKET_SIZE];
    void update();
    void clientLoop();

};

IntroScene.h

#include "cocos2d.h"
#include "BaseScene.h"


class IntroScene : public cocos2d::Layer, public BaseScene
{
public:
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();

    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();

    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);

    // implement the "static create()" method manually
    CREATE_FUNC(IntroScene);

    cocos2d::Sprite* pTetrisLogo;
    cocos2d::Sprite* pCloseNormal;

    void SinglePlay(Ref* pSender);
    void MultiPlay(Ref* pSender);
    void Exit(Ref* pSender);

//  void ImageButton(Ref* pSender);

};

Solution

  • Posting here since I dont have enough reputation for commenting as of yet.

    Is there any specific reason you want it to be inherited? Cant you just make it a Singleton instead if it needs to be accessed by objects of all classes in your code?