Loading
Load tasks
To load an asset, you have to specify the bundle and asset name. Using the code below, we are loading the prefab Cube from the wonderland-tests bundle.
try {
var prefab = await AssetBundles.LoadAsset<GameObject>("wonderland-tests", "Cube");
} catch(Exception e) {
// Something wrong happened
}
Using the same logic, you can load every prefabs in a bundle.
try {
foreach (var prefab in await AssetBundles.LoadAllAssets<GameObject>("wonderland-tests")){
Instantiate(prefab);
}
} catch(Exception e) {
// Something wrong happened
}
BundledAsset
The BundledAsset class is a simple Serializable struct that helps represent an asset in a bundle. You can feed it to the LoadAsset
function and expose it in the inspector.
It also has a special ToString
function.
public class Test : MonoBehaviour {
public BundledAsset MyPrefab;
async void Start () {
Debug.Log("Loading: " + BundledAsset);
Instantiate(await AssetBundles.LoadAsset<GameObject>(MyPrefab));
}
}
Anatomy of an asset load
When you request an asset load, here is what happens under the hood:
- User requests an asset load
- Somehow, make sure we have all the bundles we need loaded
- Internally a refcount of each bundle is kept around. When a load is made directly on a bundle, we increase.
- Load the assets
- Dereference the target bundle
- Somehow, make sure we have all the bundles we need loaded
- Give the asset(s) to the user
When a bundle hits 0 references count it gets unloaded after AssetBundles.BundleAccessDuration
seconds (5 by default, you can change it directly by code). We give you this extra time to avoid unloading bundles between consecutive asset loads.
Keeping a bundle in memory
If you really know what you are doing, you can keep a bundle and its dependencies alive in memory calling AssetBundles.LoadBundle("bundle-name")
and then calling AssetBundles.UnloadBundle("bundle-name")
when you want to dereference it.
If something goes wrong or you want to make sure that all the bundles are unloaded from memory, you can call AssetBundles.ForceUnloadAllBundles()
.