I am creating a DirectX program which needs to be able to dynamically add objects into a list (or vector) for use the render function. I need to be able to access these objects through the "[]" operator which is the reason i am using vectors instead of lists. The problem is that when I add an object using push_back, it stores that object twice. For example; If the vector is empty and I'm adding the first object, it will store that object into index 0 and into index 1. this creates problems for my render function which must loop through every object and render them. This results in each object being rendered twice.
Code which defines the vector(SpriteList2) located in header file:
class Level1 : public Dx11DemoBase// Define Level1 Class
{
public:
vector<Sprite1> SpriteList2;//Define Vector
};
Code to add the objects located in cpp file:
bool Level1::LoadContent()//funtion in the Level1 class
{
Sprite1 Sprite_1({0.0f, 0.0f, 3.0f});//Define Sprite Object
SpriteList2.push_back(Sprite_1);//Add Sprite Object to Vector
Sprite1 Sprite_2({ 100.0f, 00.0f, 2.0f });//Define Sprite Object
SpriteList2.push_back(Sprite_2);//Add Sprite Object to Vector
Sprite1 Sprite_3({ 100.0f, -50.0f, 1.0f });//Define Sprite Object
SpriteList2.push_back(Sprite_3);//Add Sprite Object to Vector
return true;
}
Code to loop through the objects located in cpp file:
void Level1::Render()//funtion in the Level1 class
{
for (Sprite1 sprite : SpriteList2)//Loop through Vector
{
//Code to use the "sprite" object in rendering functions
worldMat = sprite.GetWorldMatrix();//Retrieve values from each sprite object
}
}
note The code which adds the objects (shown above) is located in a separate cpp file and the vector is defined in a header file.
I have tried with different types (ex:int) with the same result. This problem does not occur if the vector is defined outside of the header file but the vector has to be defined inside the header file so that the render function can access it.