C++ Cannot get value of global variable in cocos2d-x

谁说胖子不能爱 提交于 2019-12-25 02:42:47

问题


I have a problem when working with CCArray in cocos2d-x. I declare CCArray *arrCs, on the top, in init() function I set value for arrCs, but after I get value from it in touch event, it has nothing. Please help me, thank all.

In MainGame.cpp

int radius= 32;
float scaleImage= 0.5;
int nItem= 60;
float pMargin= 5;

int limitTime= 70;
float timeWaiting= 8;
bool opTouch= true;
int lastIndex= -1;
Size visibleSize;

CCArray *arrCs;

bool MainGame::init(){
    arrCs= CCArray::create();

    int xx= pMargin+ radius;
    int yy= pMargin+ radius;

    int inLabel= 0;
    for (int i=0; i<nItem; i++) {
        inLabel= i;
        if (i>((nItem/2)-1)) {
            inLabel= i-(nItem/2);
        }

        CCString *iconName= CCString::createWithFormat("ricon_%i.png", inLabel);
        Sprite *cs= CCSprite::create(iconName->getCString());
        cs->setPosition(Point(xx, yy));
        cs->setTag(-1);
        cs->setScale(scaleImage);    

/*****SET VALUE FOR arrCs ******************/
        arrCs->addObject(cs);

        this->addChild(cs, (1+ rand()%3));

        xx= xx+ (radius*2)+ pMargin;
        if (xx+ (radius/2)> visibleSize.width) {
            xx= radius + pMargin;
            yy= yy+(radius*2)+ pMargin;
        }
    }
}




void MainGame::onTouchesEnded(const std::vector<Touch*>& touches, Event* event){
 /******** arrCs has nothing ************/
      for (int i=0; i< arrCs->count(); i++) {
      }
}

回答1:


CCArray is an autorelease object (see the create method) and is destroyed when leaving the init method. Please call retain on your array (arrCs->retain()) in your init method and you should get the expected result in onTouchesEnded.

Regards, Laurent



来源:https://stackoverflow.com/questions/21888282/c-cannot-get-value-of-global-variable-in-cocos2d-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!