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

Author Topic: Returning a sprite as an object comes out as a white square.  (Read 1852 times)

0 Members and 1 Guest are viewing this topic.

Aerine

  • Newbie
  • *
  • Posts: 10
    • View Profile
Returning a sprite as an object comes out as a white square.
« on: April 16, 2017, 09:04:53 pm »
I have a draw class that creates and returns a sprite. However when i use the assignment operator all i get is a white square for the newly created sprite. Simply creating a sprite without using the function works so i know the code in my function is good.

sf::Sprite & Draw::drawTowerSprite()
{
        std::cout << "cake" << std::endl;
        sf::Texture towertexture;
        if (!towertexture.loadFromFile("tower.png", sf::IntRect(0, 0, 32, 32)))
        {
                std::cout << "Couldnt load Monster" << std::endl;
        }
        sf::Sprite spritetower1;
        spritetower1.setTexture(towertexture);
        spritetower1.setPosition(50, 50);
        return spritetower1;
}

// then in another function

Draw objects;
   newsprite = objects.drawTowerSprite(); // this will create the sprite but a white square. Does it have no texture?
« Last Edit: April 16, 2017, 09:14:04 pm by Aerine »

Aerine

  • Newbie
  • *
  • Posts: 10
    • View Profile
Re: Returning a sprite as an object comes out as a white square.
« Reply #1 on: April 16, 2017, 10:42:40 pm »
Uggh i realize now that textures dont survive ......... I wonder if im going to run into an raii problem later on when i try to handle this.

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Returning a sprite as an object comes out as a white square.
« Reply #2 on: April 17, 2017, 01:44:59 am »
You can just store the texture object in the main function and pass (by reference or pointer) it to the objects that use it. That way, it will last the entire length of the program but is not global so its destruction can be predicted.

Note that this carries for all resources, which is why a (more) global resource manager is often used. By "more global", I mean in the main function or top level of the game/application class, not outside of the main function.

If you use pointers to allocate memory for the resources, use smart pointers. (std::unique_ptr<sf::Texture> texture)
Alternatively, just use vectors of each resource. The actual item data (the resource) still ends up in the heap. (std::vector<sf::Texture> textures)
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*