Firstly, i am sorry if the title does not properly describe my problem, but i could not think of a better one. =/
I am trying to make a game where all entities that I need to draw on the screen are children of an Actor class.
The actor class has a virtual function called “virtual void drawMe()” that is overridden by the children to specify how it should be drawn.
Ergo, at the end of the game loop, I want to draw all actors. I created a “vector allActors” to help me with this and every time I create a new actor I do this: “allActors.push_back( &newActor )“. So far so good (I think).
To draw them at the end of the loop I iterate through all elements in allActors and call “allActors[i]->drawMe()” for each one.
But I discovered that this method will not work for actors that I created locally, like the bullets created when the character shoots (they are created inside an if statement).
I think it is because while I save the address of the bullets in the allActors vector, the actors themselves are destroyed after the if statement ends, so it’s an address to nothing.
example:
if ( characterShot == true)
{
Bullet newBullet;
allActors.push_back( &newBullet );
characterShot = false;
}
I have no idea of how to do this in a way that it works, because I can only create the bullet actors IF the character shoots!
Please help me figure out a better and more functional way to do what I want.
Thank you in advance!
Allocate the object dynamically:
Note that the lifetime management will be a genuine nightmare; you should make the container elements some sort of smart pointer (ideally
std::unique_ptr<Bullet>or some suitable base class).