lxndragreat
lxndragreat

Reputation: 68

Objects becoming null in C++ vector<Object*>

I'm working on a game in C++, and have a player object and a bullet object. I have a std::vector collection for both kinds of object, defined earlier in my code like so:

std::vector<Player*> players;
std::vector<Bullet*> bullets;

My problem happens in my main game loop, where I do all of my update logic. Using a for loop to check each player and update him, I get any bullets he has spawned and add them to the bullets vector.

    // update players
    for (int i = 0; i < players.size(); ++i){
        Player *player = players[i];
        player->Update(delta);
        // get bullets
        for (int b = 0; b < player->Bullets.size(); ++b){
            // THIS IS WHERE THINGS GET WEIRD FOR PLAYER 2
            Bullet *bull = player->Bullets[i];
            bullets.push_back(bull);
        }
        player->Bullets.clear();
    }

While my first player works fine - he can shoot as much as he wants - when you get to the second player, making him shoot causes an EXC_BAD_ACCESS later on when I iterate through the bullets vector. As I was stepping through with a debugger (using Xcode), when I get to the part below my comment ("// THIS IS WHERE THINGS GET WEIRD FOR PLAYER 2"), I notice that the bullet is NULL and the player is NULL as well. Somewhere between calling that player's update method and where I pull the bullets out, things go horribly wrong.

I've been debugging this for several hours now, and I'm wondering what I am missing.

Thanks!

Upvotes: 1

Views: 470

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254621

It's a simple typo:

Bullet *bull = player->Bullets[b];
                               ^ not i 

You could avoid this kind of mistake using range-based loops (C++11 or later):

for (Player * player : players) {
    player->Update(delta);
    for (Bullet * bullet : player->Bullets) {
        bullets.push_back(bullet);
    }
    player->Bullets.clear();
}

and/or replacing the inner loop with

bullets.insert(bullets.end(), player->Bullets.begin(), player->Bullets.end());

Upvotes: 4

Related Questions