2016-03-12 94 views
0

我每2秒安排一個叫做Enemyshoot()的函數。在該函數中,我訪問存儲所有敵方對象的「enemies」矢量中的隨機對象。同時,敵人在兩秒鐘內被摧毀。我發現,當我安排enemyshoot()函數時,它可能會訪問已經銷燬的敵方物體,它會報告EXC_BAD_ACCESS。我該怎麼辦?cocos2d日程安排函數導致EXC_BAD_ACCESS

std::vector<Enemy*> enemies; 


    this->schedule(schedule_selector(GameScene::enemyShoot), ENEMY_SHOOT_FREQUENCY); 


    void GameScene::enemyShoot(float dt) { 
    auto random = int(CCRANDOM_0_1()*(enemies.size()-1)); 
    Enemy *tempEnemy = enemies.at(random); 
    new EnemyMissle(this,tempEnemy->enemy->getPosition().x,tempEnemy->enemy->getPosition().y); 
    } 

//this is where I delete the enemy object 

    if((ENEMY_COLLISION_BITMASK==a>getCollisionBitmask()&&PLAYER_MISSLE_COLLISION_BITMASK==b->getCollisionBitmask())||(ENEMY_COLLISION_BITMASK==b->getCollisionBitmask()&&PLAYER_MISSLE_COLLISION_BITMASK==a->getCollisionBitmask())){ 

     //add the score and refresh the score label 
     score+=10; 
     __String *tempScore = __String::createWithFormat("score: %i",score); 

     //traversing all the enemy objects to find the collided enemy 
     scoreLabel->setString(tempScore->getCString()); 
      for(int i=0;i<enemies.size();i++){ 
      if((enemies.at(i)->enemy->getPhysicsBody()==b)) 
       enemies.erase(enemies.begin()+i); 
      } 
     remainingEnemies--; 
     this->removeChild(b->getOwner()); 
     this->removeChild(a->getOwner()); 

     //if it is the last enemy spaceship, go to the game over scene. 
     if (enemies.size()==0)GameScene::GoToGameOverScene(score); 
    } 

回答

0

您應該創建敵人的陣列,以刪除在循環刪除它們,而不是和解析該數組後,真正刪除它們