cocos2d调度功能导致EXC_BAD_ACCESS

时间:2016-03-12 03:11:31

标签: cocos2d-iphone

我每2秒安排一个名为Enemyshoot()的功能。在函数中,我访问" enemies"中的随机对象。存储所有敌人物体的矢量。与此同时,敌人在两秒钟内被摧毁。我发现当我安排enemyshoot()函数时它可能会访问已经被破坏的敌人对象,它会报告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);
    }

1 个答案:

答案 0 :(得分:0)

您应该创建一个要删除的敌人数组,而不是在循环中删除它们并解析此数组后才能真正删除它们