Zbadrawy
Zbadrawy

Reputation: 13

Building a game with SFML and texture refuses to draw

I'm using SFML 2.3 to build a game and I have an extremely odd issue. I have two different texture files, both .png, but one of them refuses to be drawn.

I don't get any error message either way. For some reason TextureA works and appears just fine but TextureB doesn't draw.

I made sure the code is correct, checked for caps, I have both in the same folder, and tried everything. I even tried entering TextureA in place of TextureB and TextureA was drawn just fine. I think the problem may be with the .png file itself but I can't figure out what it is.

Thanks in advance!

Upvotes: 0

Views: 89

Answers (1)

Guillaume Racicot
Guillaume Racicot

Reputation: 41750

There is a catch with textures and SFML. Sprites assumes that they are not owner of the texture resource. By that, you must assure that the texture still exists when you try to draw. Look at this code here:

sf::Sprite makeSprite() {
    sf::Texture tex;
    tex.loadFromFile("someTexture.png");

    sf::Sprite sprite;

    sprite.setTexture(tex);

    // You indeed return the sprite, but tex is going out of scope here.
    return sprite;
}

// further code will draw the sprite as a white square.

Instead, try to keep texture in a list of loaded textures. You could keep a vector somewhere or simply put your texture as static variable in the function makeSprite. I strongly recommend not use static or global variables as they are first sign of design flaw, but it's still a valid solution.

Upvotes: 2

Related Questions