Reputation: 13
I'm using SFML with C++. The problem is that nothing is drawn on the window if I use functions, but I can draw when I make the text local. Please tell me what did I do wrong
Code:
In the game.cpp file
void Game::loadMenuText(sf::Font f, std::string textString, int x, int y, sf::Text *tex){
tex->setFont(f);
tex->setCharacterSize(16);
tex->setFillColor(sf::Color(0x225522ff));
tex->setStyle(sf::Text::Bold);
tex->setString(textString);
tex->setPosition(x,y);
}
void Game::loadFont(){
if (!font.loadFromFile("font/arial.ttf"))
{
std::cout<<"Font could not be loaded";
}
}
void Game::run(){
loadFont();
sf::Text ButtonTex;
loadMenuText(font,"Play",20,20,&ButtonTex);
menuText.push_back(ButtonTex);
window.draw(menuText[0]);
}
in the game.hpp file
private:
sf::Font font;
std::vector<sf::Text> menuText;
public:
void run();
void loadFont();
void loadMenuText(sf::Font, std::string, int, int, sf::Text *tex);
Hopefully I did not forget to add anything
Upvotes: 1
Views: 442
Reputation: 20969
Read reference about Text
It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text).
your problem is that you are passing local variable sf::Font f
in function loadMenuText
to tex
so it leads to undefined behaviour, tex
refers to resource which was deleted.
Change your signature to:
void Game::loadMenuText(sf::Font& f, std::string textString, int x, int y, sf::Text *tex){
^^^
//..
then you will be using original font
object instead of its copy.
Upvotes: 3