SFML community forums

Help => General => Topic started by: trapped_in_a_corner on October 04, 2022, 03:11:46 pm

Title: Texture wont load
Post by: trapped_in_a_corner on October 04, 2022, 03:11:46 pm
Hello everyone, im beginner in SFML and i stuck in a problem. I want to refactor my code and wrote function that generate my sprites:
Sprite createSprite(const std::string path, float posX, float posY)
{
    Image image;
    image.loadFromFile(path);
    Texture texture;
    texture.loadFromImage(image);
    Sprite sprite;
    sprite.setTexture(texture);
    sprite.setPosition(posX, posY);
    return sprite;
}
 

Then i call it in main:
Sprite machineSprite = createSprite("images/machine.png", 20, 15);
 

then i call function to draw :
window.draw(machineSprite);
. And then i see next picture - my figures without images: (in attachments with white textures)

And before refactoring my code looked like this: (in attachments with normal graphics)
Image machineImage;
    machineImage.loadFromFile("images/machine.png");
    Texture machineTexture;
    machineTexture.loadFromImage(machineImage);
    Sprite machineSprite;
    machineSprite.setTexture(machineTexture);
    machineSprite.setPosition(20, 15);
 

What am I doing wrong, thanks in advance!
Title: Re: Texture wont load
Post by: eXpl0it3r on October 04, 2022, 03:25:03 pm
The official tutorial has a dedicated section for this common mistake fittingly called "white square problem" and it happens when you destroy the texture used with the sprite. :D

https://www.sfml-dev.org/tutorials/2.5/graphics-sprite.php#the-white-square-problem

The texture has to exist as long as you want to use it with a sprite.