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

Author Topic: Texture wont load  (Read 803 times)

0 Members and 1 Guest are viewing this topic.

trapped_in_a_corner

  • Newbie
  • *
  • Posts: 1
    • View Profile
    • Email
Texture wont load
« 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!

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10820
    • View Profile
    • development blog
    • Email
Re: Texture wont load
« Reply #1 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.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/