Reputation:
I am making an sfml framework, in the framework there is a makeSpr() function. The function has the normal code for creating a sprite inside of it, but draws a white square. I have used the texture on a different sprite, which isn't drawn using the function. It draws it normally.
makeSpr() function:
sf::Sprite makeSpr(sf::Texture tex, int x,int y, int sizeX,int sixeY) {
sf::Sprite spr;
spr.setTexture(tex);
spr.setScale(sizeX,sizeY);
spr.setPosition(x,y);
return spr;
}
Use of makeSpr to assign it to a Sprite ():
sf::Sprite sprTest = makeSpr(texTxtBox, 100,100, 5,5);
Drawing the sprite in the main loop between window.clear() and window.diplay()
window.draw(sprTest);
The texture works well if I draw it normally without the framework.
sf::Sprite sprTxtBox;
sprTxtBox.setTexture(texTxtBox);
Upvotes: 2
Views: 154
Reputation: 1184
Pass tex
by const reference:
sf::Sprite makeSpr(const sf::Texture& tex, int x,int y, int sizeX,int sixeY)
When you write sf::Sprite makeSpr(sf::Texture tex, ...
and call sf::Sprite sprTest = makeSpr(texTxtBox, ...
, tex
is actually a copy of texTxtBox
, and it gets free after return spr;
in makeSpr
, hence your spr
now has an invalid texture (already destroyed), hence it draws only white. What you want is passing texTxtBox
itself, by passing by (const) reference, and you have to make sure that texTxtBox
out-live sprTest
.
Upvotes: 2