Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Texture object defined in a function  (Read 1210 times)

0 Members and 1 Guest are viewing this topic.

HaydoMaydo

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
Texture object defined in a function
« 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
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

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Texture object defined in a function
« Reply #1 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.
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

HaydoMaydo

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
Re: Texture object defined in a function
« Reply #2 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.

 

anything