In some projects, when we are working with a lot of assets, we may need to be able to programmatically get one/load one using its path. This happened to us when we were working on a big project, in which we had a lot of assets automatically imported from FBX files and we needed to be able to instantiate them using their name at runtime.
In this short tutorial we present how we’ve managed to do it, and especially how we were able to programmtically load an asset by its path.
We had to create a blueprint to specifically load one asset or another by specifying its name. We decided to use a Datatable in which all assets informations are stored including its path in the project and its name.
Finally, we used the AssetRegistry to load the asset and get a reference using its path. Here’s how it’s done.
The AssetRegistry is an editor subsystem which gathers information about unloaded assets asynchronously as the editor loads.
This information is stored in memory so the editor can create lists of assets without loading them.
The Content Browser uses the AssetRegistry while we are developping with the UE editor. But, we will use the AssetRegistry system to load files once the game is packaged.
First, we have to get the AssetRegistry by calling the corresponding Blueprint node :
You can see here all the functions provided by the AssetRegistry. For this tutorial we’ll only use the GetAssetsByPath function but you can explore and try to use the others by your own.
For our project, the StaticMesh we want to load will all be located in a particular folder. We will retrieve all assets in this folder and then filter them by name or type.
We fill the “PackagePath” using the path where the assets are located. In the present case (cf. the screenshot below), it is “/Game/Meshes/Train”.
In this example (we are in debug mode), we can see the list of assets retrieved by the function.
Deal with assets data
We can now iterate on our assets and find one (or more) assets which fit our needs. In the example below, we try to find a StaticMesh matching a particular name. Once this asset found, we can get it and cast it to the wished type to use it.
This quick introduction to how we can use the AssetRegistry to get references to unloaded meshes is over.
Of course you can explore by your own all the functions in the AssetRegistry.
If you only need to get one particular asset by its name maybe the GetAssetByObjectPath function may be enough.
Also, remember to configure Unreal to include these dynamically loaded files into the packaged game if you want to be able to load them at runtime.
Good luck 😉