Runtime Asset Swapping
You can dynamically swap assets in your Rive animations at runtime using the CustomAssetLoaderCallback
. This lets you change fonts, images, or audio files while your Rive file is playing, making it possible to create dynamic visuals.
Setting Up Asset Loading
To swap assets at runtime, provide a callback when loading your Rive file:
Your callback will be invoked whenever the runtime needs to load an asset. The callback should return true
if you’ve handled the asset loading, or false
to let the runtime handle it using the default loading behavior.
Here’s an example showing how you might swap a font at runtime:
Overload With Fallback
An overload of Rive.File.Load()
includes a fallbackToAssignedAssets
parameter.
If set to true
and your custom loader doesn’t handle a certain asset, the runtime will look for references assigned to your Rive asset in the Unity Inspector and automatically load them if they exist. This is handy when you only want to replace some assets and rely on default references for the rest.
Asset Types
You can swap these types of assets at runtime:
-
FontOutOfBandAsset
: For font files -
ImageOutOfBandAsset
: For image files -
AudioOutOfBandAsset
: For audio files
Asset Reference Types
When handling assets in your callback, you’ll need to check the type of the EmbeddedAssetReference
before setting the asset. Each asset type has its own reference class with specific setter methods:
Memory Management
When working with runtime asset swapping, we recommend following these best practices:
-
Always call
Load()
on your Out-Of-Band asset before using it in the callback -
Dispose of resources properly:
-
Call
Unload()
on your assets when they’re no longer needed -
Call
Dispose()
on the Rive file when you’re done with it
-
Creating Out-of-Band Assets Dynamically
If you have an asset that isn’t in your Unity project at build time (for example, if you’re loading an image from a CDN), you can create an out-of-band asset at runtime using the OutOfBandAsset.Create<T>()
method. Here, the bytes
parameter should be the raw file data for the asset.
This works for fonts, images, and audio, as long as you use the appropriate type (FontOutOfBandAsset
, ImageOutOfBandAsset
, or AudioOutOfBandAsset
).
Was this page helpful?