-
Notifications
You must be signed in to change notification settings - Fork 1
Resources and Assets
Assets like models, sound effects or others are a very important aspect of developing games. Basalt has a utility class for loading, caching, retrieving and unloading these resources: The ResourceCache
class.
For this guide, we'll be using the Basalt.Raylib
package and the extension methods it has for the ResourceCache.
Note
Extension methods will be accessed through ResourceCache.Instance
due to limitations. In the future with .NET 9 and above, this might change.
Loading resources through the utility class can be done using ResourceCache.LoadResourceFromFile
.
// Not recommended, but works.
ResourceCache.LoadResourceFromFile("myResource", "path/to/my/datafile.json");
var resource = ResourceCache.GetResource<MyDataType>("myresource"); // Keys are case-insensitive
// Recommended approach.
ResourceCache.LoadResourceFromFile("myresource2", "path/to/my/otherdata.something", (filepath) => MyCustomLoadingMethod(filepath));
var resource2 = ResourceCache.TGetResource<OtherType>("myresource2");
// Another method
if(ResourceCache.TryGetResource<OtherType>("myresource2", out OtherType result)
{
result.DoSomething();
}
Warning
Loading resource directly from the cache is not recommended unless it is a more specific extension method like the ones provided by Basalt.Raylib
, but it is an option. By default it will consider everything a JSON file.
Some packages like Basalt.Raylib
give extensions to loading specific models. In this case, this package will add extension methods for loading Models, Sounds, etc.
ResourceCache.Instance.LoadShader("mycoolshader", fragShaderPath, vertShaderPath");
// Both are valid
Raylib_cs.Shader shader = ResourceCache.Instance.GetShader("mycoolshader");
Raylib_cs.Shader shader2 = ResourceCache.GetResource<Shader>("mycoolshader");
For any resource, no matter if an extension method was used or not, can be unloaded with ResourceCache.UnloadResource(resourceKey)
. Using the previous code as example.
ResourceCache.UnloadResource("myresource");
ResourceCache.UnloadResource("mycoolshader");
var shader = ResourceCache.Instance.GetShader("mycoolshader"); // null
var data = ResourceCache.GetResource<MyDataType>("myresource"); // null
You may also unload everything using ResourceCache.Clear()
.
By default, the engine and basalt renderers will unload the resources automatically upon shutdown.
Using ResourceCache.CacheResource(string resourceName, object resource)
you may also cache an existing instance of an object.
Just like Get
and Load
methods, there are also extension methods for caching Raylib models, shaders, etc.
var something = Utility.LoadSomething();
ResourceCache.CacheResource("something", something);
// Using Basalt.Raylib extensions
Model cube = Raylib_cs.Raylib.LoadModelFromMesh(Raylib_cs.Raylib.GenMeshCube(1, 1, 1));
ResourceCache.Instance.CacheModel("coolcube", cube);