Sign in to follow this  

Create varying number of game objects & their names in a loop?

This topic is 4175 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm working on my first game from scratch and having a little trouble coming up with what seems like a simple loop that creates game objects. Say I know the number of "badguy" objects I want to create in a game beforehand. Each badguy object needs a unique name, and the number of badguys will vary from level to level. Is it possible to create a loop that: -generates names for a badguy object from a known number -creates an instance of the badguy using the newly created name I imagine the code would be something like: int numberOfBadguys = 5; for (int i= 0; i < numberOfBadguys; i++) //some kind of code here that increments a variable that could be used as a name generatedname = new badguy(); generatedname->create(); So the badguy #1 object would be named "000" and badguy #2 could be named "001," etc up to 005. It almost feels like I want to generate the name of an object from another variable, but It doesn't seem possible and I'm certain there's an easier way to create varying numbers of game objects. I've read through a few books and plenty of tutorials, but they don't really give examples with dynamic names. :( The question seems pretty basic, so thanks for your time... and patience! :D

Share this post


Link to post
Share on other sites
Use an array or vector, like so.


std::vector<badguy> BadGuyList; //Create a new vector of type badguy
for (int i = 0; i < 5; i++){
BadGuyList.push_back(badguy()); //Add a new badguy to the list
}


Then simply access badguys in the list just like an array. BadGuyList[0].DoStuff();

By the way, you only use -> when you're working with pointers. That same code with memory management would look like so:



std::vector<badguy*> BadGuyList; //Create a new vector of type badguy
for (int i = 0; i < 5; i++){
BadGuyList.push_back(new badguy()); //Add a new badguy to the list
}


and when you're done with your vector of badguys, you can clean it up like so.


for (int i = 4; i >= 0; i--){
delete BadGuyList[i];
sg.erase(BadGuyList.begin() + i);
}


If you need further explanation on something you don't understand, just ask.

Share this post


Link to post
Share on other sites
ScottC is right on target. A vector is exactly what you need.

Share this post


Link to post
Share on other sites
Sign in to follow this