SFML community forums

Help => General => Topic started by: HaydoMaydo on April 18, 2020, 11:02:20 pm

Title: Texture object defined in a function
Post by: HaydoMaydo on April 18, 2020, 11:02:20 pm
Hello, I am trying to make a game in SFML, and have this annoying texture problem. I have a load function in one of my implementation files, and it loads a texture from a .png, and stores it in a member variable (so it does not get garbage collected as soon as the function ends). I am aware of the white square problem, and I believe that is the error I am receiving. https://www.sfml-dev.org/tutorials/2.1/graphics-sprite.php#the-white-square-problem (https://www.sfml-dev.org/tutorials/2.1/graphics-sprite.php#the-white-square-problem)
If I load my texture globally, it works. but I do not understand why it does not work, since the texture is a private member variable of the Screen class.
I have checked and the texture is loaded in properly, but when it is time to render in another function, It does not work. It works if I load my sprite in the render function from a texture, but that does not seem very efficient.
void Screen::titleScreenLoad()
{

    if (!m_backgroundTexture.loadFromFile("assets/home_screen_background.png"))
    {
        std::exit(1);
    }

    sf::Sprite sprite(m_backgroundTexture);
    m_vecOfSprites.push_back(sprite);
}

void Screen::titleScreenRender() const
{
    for (int i = 0; i < m_vecOfSprites.size(); ++i) // loops through all sprites and displays
    {
        m_window->draw(m_vecOfSprites[i]);
    }
    m_window->display();
}
 
The full code is available here: https://github.com/HaydoMaydo/PA-6 (https://github.com/HaydoMaydo/PA-6)
Title: Re: Texture object defined in a function
Post by: Hapax on April 19, 2020, 12:30:58 am
Your full code is very different. Your texture seems to be stored in a vector. This is likely the problem. Vectors can move in memory when their data change. This invalidates sprite's texture pointers.
Title: Re: Texture object defined in a function
Post by: HaydoMaydo on April 19, 2020, 08:26:29 pm
Your full code is very different. Your texture seems to be stored in a vector. This is likely the problem. Vectors can move in memory when their data change. This invalidates sprite's texture pointers.

I tried not using a vector to store the textures, and it still does not work. For some reason, it does not work unless I assign the texture to the sprite every frame.