大家都知道一个程序中只有一个导演类,eg:
CCDirector *pDirectory = CCDirector::sharedDirector();//初始化导演类。
可通过 pDirectory->属性 取得自己想要的值。
我们也可以自己设定一个类用于存储只初始化一次的量,刚开始学2dx,今天为了2个CCLayer之间传值而使用单例,设定A界面的几个参数值,当A场景切换跳转到B界面时,B需要用到A界面的这几个参数值,故单独写了个单例类用于存储数据参数。
.h:
#ifndef __ResultCar__GameData__
#define __ResultCar__GameData__
#include
#include "cocos2d.h"
class GameData : public cocos2d::CCObject {
public:
static GameData\* sharedGameData();
CC\_PROPERTY(float, myEngine, MyEngine);
CC\_PROPERTY(float, myG, MyG);
CC\_PROPERTY(float, myFrition, MyFrition);
};
.m:
#include "GameData.h"
GameData *gameData = NULL;
GameData* GameData::sharedGameData()
{
if(!gameData)
gameData = new GameData();
return gameData;
}
float GameData::getMyEngine()
{
return myEngine;
}
void GameData::setMyEngine(float engine)
{
myEngine = engine;
}
float GameData::getMyG()
{
return myG;
}
void GameData::setMyG(float g)
{
myG = g;
}
float GameData::getMyFrition()
{
return myFrition;
}
void GameData::setMyFrition(float frition)
{
myFrition = frition;
}
当我存储数据的时候可通过以下代码存储:
GameData::sharedGameData()->setMyEngine(myEngine); // myEngine是A界面的参数
这里设定了3个参数分别存储:
GameData::sharedGameData()->setMyG(myI);
GameData::sharedGameData()->setMyFrition(myFriction);
当我在B界面用到这几个参数的时候可通过如下代码来获得:
//car_myEngine car_myI car_myFrition 为B界面用于接收数据的属性值
car_myEngine = GameData::sharedGameData()->getMyEngine();
car\_myI = GameData::sharedGameData()->getMyG();
car\_myFrition = GameData::sharedGameData()->getMyFrition();
手机扫一扫
移动阅读更方便
你可能感兴趣的文章