In the SelectLevel class, there is a drawLevels function (tgui :: Gui & gui, sf :: RenderWindow & window, string name), which takes a pointer to the window and widget window for SFML and TGUI libraries, respectively.

void SelectLevel::drawLevels(tgui::Gui& gui, sf::RenderWindow& window, string name) { tgui::Label::Ptr levelTitle = std::make_shared<tgui::Label>(); levelTitle->setPosition(135, 92); levelTitle->setTextSize(22); levelTitle->setText(name); gui.add(levelTitle); } 

The bottom line is that there is a cycle:

 SelelctLevel Level; for (int i = 0; levelNameVector.size() > i; i++) { Level.drawLevels(gui, window, levelNameVector[i]); } 

I need to use the drawLevels function, but at the same time it is necessary that the instance name that comes after the type declaration tgui :: Label :: Ptr in the drawLevels function changes depending on the iteration number or at least is unique. How can this be realized?

    1 answer 1

    The variable name does not play a role here, as far as it can be seen, if it is declared inside a function, then it will only exist until the end of the function. But since it is "shared" and added to gui, it will remain in memory, but without a name.

    If you need to access this label, you will need to give it a name and make it unique. https://tgui.eu/documentation/0.8/classtgui_1_1Gui.html#aa5148777e159aed6d08dca0602cf79da

     void tgui::Gui::add ( const Widget::Ptr & widgetPtr, const sf::String & widgetName = "" ) 

    This is not the name of the variable, but the name of the widget is a string. You can then access by passing the name to the get function. https://tgui.eu/documentation/0.8/classtgui_1_1Gui.html#a820f590c4cfbc9cc59a84ab51f0dff63

     gui.add(levelTitle, "my_label1"); tgui::Label::Ptr levelTitle = gui.get("my_label1"); 

    As a result, the final function looks like this:

     void SelectLevel::drawLevels(tgui::Gui& gui, sf::RenderWindow& window, int i, string name) { tgui::Label::Ptr levelTitle = std::make_shared<tgui::Label>(); levelTitle->setPosition(135, 92); levelTitle->setTextSize(22); levelTitle->setText(name); gui.add(levelTitle, "levelLabel" + i); } for (int i = 0; levelNameVector.size() > i; i++) { drawLevel[i]->drawLevels(gui, window, i, levelNameVector[i]); }