我是Cocos2d-x的新手,我正在使用数组来保存图层上的字符精灵列表。
characterArr = CCArray::createWithCapacity(NUMBER_CHARACTERS/NUMBER_CHARACTERS_PER_SCENE);
for (int i = 1; i <= NUMBER_CHARACTERS/NUMBER_CHARACTERS_PER_SCENE; ++i)
{
CCLayer* characterLayer = CCLayer::create();
for (int j = 1; j <= NUMBER_CHARACTERS_PER_SCENE; ++j)
{
int characterID = j + NUMBER_CHARACTERS_PER_SCENE*(i - 1);
CCString* characterName = (CCString::createWithFormat("ChooseCharacterScene/c%i.png", characterID));
CCSprite* character = CCSprite::create(characterName->getCString());
CCMenuItemSprite* characterItem = CCMenuItemSprite::create(character,
character,
this,
menu_selector(ChooseCharacterScene::CharacterTouched));enter code here`
characterItem->setTag(characterID);
CCMenu* menu = CCMenu::create(characterItem, NULL);
characterLayer->addChild(menu, GR_FOREGROUND);
characterArr->addObject(characterLayer);
然后在menu_selector函数中,我使用函数objectAtIndex()函数来获取玩家触摸的图层的索引,但是当我测试时,有时它工作,有时候,字符数组是空的。有人可以帮我解决这个问题吗?感谢。
int layerIndex = characterTouchedID/NUMBER_CHARACTERS_PER_SCENE;
if (characterTouchedID % NUMBER_CHARACTERS_PER_SCENE == 0) {
layerIndex--;
}
((CCLayer* )characterArr->objectAtIndex(layerIndex))->addChild(character, GR_MIDDLEGROUND);
答案 0 :(得分:0)
我发现此错误的原因是CCArray是一个自动释放对象。从这里引用类似的错误:C++ Cannot get value of global variable in cocos2d-x