I'm currently writing a small game, needing some advice for things I could do better on this resource management system. Speed is not crucial, and I have no memory budget.
The goal is to load and store resources so they can be reused and accessed with a string. That way, all resources are loaded at once, and can be reused by this singleton from anywhere else in the code. This system currently works, I'm just looking for ways to improve it or better leverage STL's features.
The Resource
class
class Resource
{
public:
Resource();
virtual ~Resource();
virtual void loadResource() = 0;
virtual void unloadResource() = 0;
void setResourceId(unsigned id);
unsigned getResourceId() const;
void setResourcePath(const std::string& path);
std::string getResourcePath() const;
protected:
unsigned mResourceId;
std::string mResourcePath;
};
It's a simple base class with getters and setters, along with pure virtual loadResource()
and unloadResource()
functions that each derivative will override.
The ResourceManager
class
class ResourceManager : public Singleton<ResourceManager>
{
public:
ResourceManager();
virtual ~ResourceManager();
void addResource(Resource* resource, const std::string& name, const std::string& path);
template <typename T>
T* getResource(const std::string& name) {
return dynamic_cast<T*>(mResources.find(name)->second);
}
static ResourceManager& getInstance();
static ResourceManager* getInstancePtr();
private:
std::map<std::string, Resource*> mResources;
};
The addResource
implementation
void ResourceManager::addResource(Resource* resource, const std::string& name, const std::string& path)
{
resource->setResourcePath(path);
resource->setResourceId(mResources.size());
resource->loadResource();
mResources.insert(std::pair<std::string, Resource*>(name, resource));
}
The unloadResource
function is called for every Resource
in ResourceManager
's destructor.
Usage example: loading the resource (with a hypothetical Texture
class)
mResourceManager->addResource(new Texture, "test", "Resources/test.png");
Usage example: accessing the resource
mResourceManager->getResource<Texture>("test");
Like I said earlier, speed/memory isn't crucial, so all solutions are welcome.
ResourceManager
? \$\endgroup\$Core
class in the game controls the starting up and shutting down of theseManager
classes, and they're singletons so the instances can be accessed from anywhere else in the game. \$\endgroup\$