Posted at

Cocos2d-xでシングルトンによる画面間データ連携

More than 5 years have passed since last update.

やっとできたので共有しておきます♪

参考記事

Cocos2d-xでシングルトンによる画面間データ連携

http://xcode555.sblo.jp/article/62645292.html

(この時点では.cppが貼り間違いでした…)

Singleton in cocos2d-x Android

http://stackoverflow.com/questions/9434436/singleton-in-cocos2d-x-android


GameManager.h

//

// GameManager.h
// SingletonTEST
//
// Created by prototechno on 2013/02/20.
//
//

#ifndef __SingletonTEST__GameManager__
#define __SingletonTEST__GameManager__

typedef enum{
GameModeMenu ,
GameModeNagasa ,
GameModeKasa ,
}GameMode;

#include "cocos2d.h"

class GameManager
{
private:
GameManager();
static GameManager* m_mySingleton;

public:
static GameManager* sharedGameManager();

GameMode gameMode;

int count;

float gameTime;

};

#endif /* defined(__SingletonTEST__GameManager__) */



GameManager.cpp

//

// GameManager.cpp
// SingletonTEST
//
// Created by prototechno on 2013/02/20.
//
//
#include "SimpleAudioEngine.h"
#include "GameManager.h"

using namespace cocos2d;
using namespace CocosDenshion;

//All static variables need to be defined in the .cpp file
//I've added this following line to fix the problem
GameManager* GameManager::m_mySingleton = NULL;

GameManager::GameManager()
{

}

GameManager* GameManager::sharedGameManager()
{
//If the singleton has no instance yet, create one
if(NULL == m_mySingleton)
{
//Create an instance to the singleton
m_mySingleton = new GameManager();
}

//Return the singleton object
return m_mySingleton;
}


使い方はこんな感じ… gameTimeでタイマーを実装した時の記録。


sample.cpp


#include "GameManager.h"

void Play5::countTimer(float time)
{
GameManager::sharedGameManager()->gameTime += time;

//時間を表示する
CCString* timeString = CCString::createWithFormat("%8.0f秒", GameManager::sharedGameManager()->gameTime);
CCLabelTTF* timerLabel = (CCLabelTTF*)this->getChildByTag(kTagTimerLabel);
timerLabel->setString(timeString->getCString());
}