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

Author Topic: My texture holder gets deleted although still in scope  (Read 1418 times)

0 Members and 3 Guests are viewing this topic.

affenmehl8

  • Newbie
  • *
  • Posts: 3
    • View Profile
    • Email
My texture holder gets deleted although still in scope
« on: June 13, 2019, 04:37:30 pm »
So I'm new to SFML. I read a lot of post, but I really  don't get it.
I wrote an texture holder:
Quote
class tile_texture_holder {
private:
   sf::Texture tx;
public:
   tile_texture_holder(type a) {
      switch (a) {
      case type::desert:
         tx.loadFromFile("C:/Users/Andreas/source/repos/conquer/Media/desert.png");
         break;
      case type::grass:
         tx.loadFromFile("C:/Users/Andreas/source/repos/conquer/Media/grass.png");
         break;
      case type::mountain:
         tx.loadFromFile("C:/Users/Andreas/source/repos/conquer/Media/mountain.png");
         break;
      case type::water:
         tx.loadFromFile("C:/Users/Andreas/source/repos/conquer/Media/water.png");
         break;
      }
   }
   sf::Texture ret_texture() {
      return tx;
   }

   ~tile_texture_holder() {
      std::cout << "///////////////////////HOLDER DELETED!!!/////////////////////" << std::endl;
   }
};

And I tried to load a sprite with it in different ways....
For example:
Quote
tile_texture_holder t(type::desert);
      sf::Sprite s;
      s.setTexture(t.ret_texture());
(in the same function, where I draw the sprite)
I always get the white box being drawn. And I really dont get why the texture_holder is getting deleted.
BTW type is an enum.

I hope somebody can help me solve my issue!

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11033
    • View Profile
    • development blog
    • Email
Re: My texture holder gets deleted although still in scope
« Reply #1 on: June 13, 2019, 05:23:06 pm »
You create a new, local tile_texture_holder which creates a texture, then you set the texture to the sprite.
But since the tile_texture_holder is local, it will be destroyed as soon as you run out of scope, destroying the texture and thus the reference from the sprite to the texture becomes invalid.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/