2014-02-28 54 views
0

我是Cocos2d-x的新手,我正在使用數組來保存圖層上的字符精靈列表。未裝入數組 - 「索引超出objectAtIndex()範圍」

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); 

回答