Search code examples
c++cocos2d-x

Array is not loaded -"index out of range in objectAtIndex()"


I am new to Cocos2d-x and I am using an array to save a list of character sprites on a layer.

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

Then in menu_selector function, I use function objectAtIndex() function to get the index of layer which player touched to but when I test, sometimes it worked, and sometimes, the character array was empty. Can anybody help me to solve this problem? Thank.

int layerIndex = characterTouchedID/NUMBER_CHARACTERS_PER_SCENE;
    if (characterTouchedID % NUMBER_CHARACTERS_PER_SCENE == 0) {
      layerIndex--;
    }
    ((CCLayer* )characterArr->objectAtIndex(layerIndex))->addChild(character, GR_MIDDLEGROUND);

Solution

  • I found the reason for this error was that CCArray is an auto release object. Reference from here with similar error : C++ Cannot get value of global variable in cocos2d-x