Im trying to do a vector of struct elements to draw them in RenderWindow;
my struct for non-ui objects:
struct element{
sf::Texture texture;
sf::Sprite sprite;
sf::IntRect rect;
sf::Text text;
};
my struct for ui objects:
struct uiElement: element{
sf::Text text;
bool clickable;
};
Im adding elements like that:
std::vector<uiElement> ui;
uiElement el;
el.texture.loadFromFile("../res/textures/background.jpg");
ui.push_back(el);
ui.back().sprite.setTexture(ui.back().texture);
and it works!But, only if my "std::vector<uiElement> ui;" has one element;
when i try to add more with cycle:
for (int i = 0;i < 4;i++){
uiElement btn;
btn.texture.loadFromFile("../res/textures/button.png");
ui.push_back(btn);
ui.back().sprite.setTexture(ui.back().texture);
}
draws only last object in my "std::vector<uiElement> ui;" and the other are just white
my drawing part of code:
for (auto & element : ui){
window.draw(element.sprite);
}
How can I fix it??
thanks in advance
At the first glance the way u use the std::vector really drags my attention, and this is what I think it's happening in ur for loop:
- create a uiElement named btn
- load its texture
- !!! push into the vector a COPY of the btn
- !!! set texture of a sprite of an ANOTHER COPY from the vector
push_back() and back(), if I'm not wrong, both takes the parameter (or returns it) by value, which means u set the sprite for a completely different obj, that u discard after. U're pushing and getting back copies, and not the original obj which u try to draw later. A way that I use most of times would be to make ur vector of pointers (uiElement*). If u're a beginner this may not be the best method since u must take care of freeing the memory after and stuff. U could, as another example, pushing into the vector after u set the sprite. Another way is to rather than using back(), get the address of the last element in vector, maybe like "&ui[ui.size() - 1]" if I'm not wrong, and change stuff on the pointer u get (pointer = &obj)