开发者

C++ Instantiate class and add name to array/vector then cycle through update functions from the array

开发者 https://www.devze.com 2023-02-03 08:29 出处:网络
I have a bunch of classes in a basic (and badly coded!) game engine that are currently instantiated in the code and have to have their individual update functions called. What I want to do is be able

I have a bunch of classes in a basic (and badly coded!) game engine that are currently instantiated in the code and have to have their individual update functions called. What I want to do is be able to create an instance of a class, pass the name to an array, and then subsequently cycle through the array to call the update functions of each class. I'm unsure as to whether or not this is an impossible or spectacularly stupid way of trying to manage objects, so please tell me if it is.

So currently I might have manually instantiated Enemy class a couple of times:

Enemy enem1;
Enemy enem2;

I then have to update them manually in the game loop:

enem1.update();
enem2.update();

What method should I use to be able to spawn and destroy instances of the enemy class during gametime? Is it possible to populate an array with instantiated names and then do something like (and i'm aware this doesn't work);

array[x].update();

Then iterate through the names in the array?

Anything that even points me in the right direction would be greatly app开发者_如何学Goreciated!


Use a std::vector<Enemy>, insert into it however many Enemys you need, and iterate over it to perform actions on all or some of the elements using std::vector<Enemy>::iterator.


//vector initialization
std::vector<Enemy> enemies;
enemies.push_back(enem1);
enemies.push_back(enem2);
enemies.push_back(enem3);
enemies.push_back(enem4);

//update code
for(std::vector<Enemy>::iterator e = enemies.begin() ; e != enemies.end() ; e++ )
{
    //treat 'e' as if it's a pointer to Enemy!
    e->update(); //this will be called for each enemy in the vector 'enemies';
}

An alternative of this for loop is this:

//update code
for(std::vector<Enemy>::size_type i = 0 ; i < enemies.size() ; i++ )
{
    //using index
    enemies[i].update();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消