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

Author Topic: How to share assets between the scenes?  (Read 176 times)

0 Members and 1 Guest are viewing this topic.

Abc

  • Newbie
  • *
  • Posts: 2
    • View Profile
How to share assets between the scenes?
« on: March 19, 2024, 09:28:28 pm »
Hello,
I am trying to create my own game engine based on SFML. I created the scenes, that has the local assets. But I don't understand how to share assets between two scenes, that could replace each other.

Approximate code:

class Level : public AbstractScene
{
public:
    Engine& engine;
    std::unordered_map<sf::Image> images

   Level()
   {
        images["img1"].loadFromFile("img1.png"); // load image
   }

    void update()
    {
         sf::Texture texture(assets.images["img1"]); // use image
         ...
         engine.setScene(new MiniLevel());
    }
};

class MiniLevel: public AbstractScene
{
public:
    Engine& engine;
    std::unordered_map<sf::Image> images;
    LevelImages& levelImages; // Level image

    MiniLevel(LevelImages& img) : // not real code
         levelImages(img)
    {
    }

    void update()
    {
         sf::Texture texture(levelImages["img1"]); // use Level image
         ...
         engine.setScene(new MiniLevel());
    }
};
 

I know I can use smart pointers to copy images from the Level to MiniLevel, but how to copy it to the Level again? Level class should load images when first created and than only copy it from the MiniLevel. Maybe should I use another class "Level" with the general assets for the scenes?

PS: sorry for my bad English.

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10821
    • View Profile
    • development blog
    • Email
Re: How to share assets between the scenes?
« Reply #1 on: March 25, 2024, 11:15:44 am »
Personally, I always recommend using something like a ResourceHolder, that ensure proper life-time of the resources, while ensure that you can easily share it, without having to reload anything.

When sharing between classes make sure you know who the owner is.
From the owner you can then provide access to the resource by passing it as references somewhere else, but you always need to make sure that the life-time is handled correctly.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

 

anything