I'm new to ECS. And I'm trying to create my own game in ECS. I want to ask what's the common way to do some resource management. For example, it's very common to load and unload images from disk in any games.
There is my resource management so far:
class Resource { public: Resource() = default; virtual ~Resource() = default; }; class Image : public Resource { const unsigned char *data; int width; int height; public: Image() = default; ~Image() { // free the memory } void load(const std::filesystem::path &path) { // load the image } }; class ResourceManager { std::unordered_map<std::string, std::unique_ptr<Resource *>> resource_map; public: void add_resource(const std::string &key, std::unique_ptr<Resource> resource) { resource_map[key] = std::move(resource); } template <typename T> T *get(const std::string &key) { // Check its type here auto iter = resource_map.find(key); if (resource_map == resource_map.end()) { return nullptr; } else { return static_cast<T *>(iter->second.get()); } } void unload(const std::string &key) { resource_map.erase(key); } }; Then I can get the resource pointer by the key string:
Image *image = resource_manager.get_resource<Image>("image.test_img"); In my opinion, it's more OO than ECS. Because it uses a global object. So, is there a better way to do that?
resource_manager.get_resourcefails to find the asset with that key, then I would really recommend to log a warning with the key-string and return a placeholder asset instead of just silently returning null. You will be glad about that later. \$\endgroup\$