Advertisement

SFML problem

Started by February 05, 2023 06:45 AM
3 comments, last by Snaked 1 year, 10 months ago

I am trying to display an image in SFML.

Here's what I have:

sf::Sprite loadSprite(std::string filename)
{
   sf::Texture texture;
   texture.loadFromFile(filename);

   return sf::Sprite(texture);
} // error: the texture is destroyed here
...
       sf::Sprite sprite = loadSprite("ufo.png");
       window.draw(sprite);

Unfortunately, the sprite doesn't display. I just get a white screen. Any ideas what is wrong?

ms75214 said:
} // error: the texture is destroyed here

Who tells you this error? Is it a compiler message? Just wondering.

Anyway - you are new to C(++) i guess?

Taking the error message seriously, i assume by constructing a sprite from the texture does not transfer ownership of the texture to the sprite.
Likely the sprite only stores a pointer (or some index) to the texture.
Thus, you must ensure the texture remains in memory eventually.
But actually your texture is a local variable inside the loadSprite function. So after the function is done, the texture will likely call its destructor, freeing up it's memory and destroying itself.
So at the point you do the draw, the texture no longer exists. (This might be fine if SFML uploads the texture to GPU memory, but i don't remember SFML well enough to tell.)

Advertisement

Spot on, Joe.

https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Sprite.php#a2a9fca374d7abf084bb1c143a879ff4a

documents sf::Sprite, with a hint to “setTexture”, which says

The texture argument refers to a texture that must exist as long as the sprite uses it. Indeed, the sprite doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the sprite tries to use it, the behavior is undefined. If resetRect is true, the TextureRect property of the sprite is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.

So the solution is to declare the texture together with wherever you eventually store the sprite, and pass that into the “loadsprite” method by reference.

as far i remember this could happens cos you declared

sf::Texture texture; //into the loadsprite() function

then the “life” of this variable is only meanwhile is into that function

a possible solution could be you declare texture variable in Global ambit this is, in the outer part globally to all code

This topic is closed to new replies.

Advertisement