SFML community forums

Help => Graphics => Topic started by: Wake on January 17, 2021, 10:26:02 pm

Title: Trying to Return a sf::Text from class to be drawn in main function
Post by: Wake on January 17, 2021, 10:26:02 pm
Hi,

Please see the attached images.

So, I've built a collision class and I want to display a rectangle object with some text in it when there is a collision between the player and the pickup item.

I got the rectangle shape to appear and disappear perfectly on collision, however when I do the same process for the sf::Text, I get an error in Virtual Studio 2019 that states:

"Unhandled exception at 0x00007FFAB2D169DB (sfml-graphics-d-2.dll) in RPG.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF."

The text draws perfectly in the main function, however, I'd like to return this from the Collision class and create a switch for different messages depending on the item being picked up.

Best,
Wake
Title: Re: Trying to Return a sf::Text from class to be drawn in main function
Post by: Hapax on January 17, 2021, 11:51:52 pm
You're creating temporary fonts, assigning them to texts and then allowing them to be destroyed. Drawing that text then attempts to use the font that no longer exists and results in an access violation.

Fonts must exist as long as they are used.

This means that it - like other (heavy) resources (like images and sound buffers) - should be loaded once (usually in advance, near the beginning) and reused. It should be stored safely and passed (by reference or pointer) around to functions that need them. They should almost never be destroyed!

Basic example:
void drawAText(sf::Font& font, sf::RenderWindow& window)
{
    sf::Text text;
    text.setFont(font);
    text.setString("SOME TEXT");
    window.draw(text);
}

int main()
{
    sf::Font font;
    if (!font.loadFromFile("font.ttf"))
        return EXIT_FAILURE;

    sf::RenderWindow window(sf::VideoMode(800u, 600u), "");

    while (window.isOpen())
    {
        // handle events here as usual

        window.clear();
        drawAText(font, window);
        window.display();
    }
}
Title: Re: Trying to Return a sf::Text from class to be drawn in main function
Post by: Wake on January 18, 2021, 01:12:31 am
Hey, thanks for the feedback!

I read another thread and it clicked!

I made sf::Font m_ItemTextFont; & sf::Text m_ItemText; member variables in my class and loaded the .ttf file to sf::Font m_ItemTextFont in my constructor. Then, I set the font of sf::Text m_ItemText; using  sf::Font m_ItemTextFont; and it worked!

For anyone else experiencing this issue, I included the screen captures here.