unity官方apiAssetBundle-LoadFromFileAsync - Unity 脚本 API
异步加载AB包
using UnityEngine;
using System.Collections;
using System.IO;
public class LoadFromFileAsyncExample : MonoBehaviour
{
IEnumerator Start()
{
var bundleLoadRequest = AssetBundle.LoadFromFileAsync(Path.Combine(Application.streamingAssetsPath, "myassetBundle"));
yield return bundleLoadRequest;
var myLoadedAssetBundle = bundleLoadRequest.assetBundle;
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
yield break;
}
var assetLoadRequest = myLoadedAssetBundle.LoadAssetAsync<GameObject>("MyObject");
yield return assetLoadRequest;
GameObject prefab = assetLoadRequest.asset as GameObject;
Instantiate(prefab);
myLoadedAssetBundle.Unload(false);
}
}
需要注意的是同一个ab包一次只能加载一个,不可以同时加载,
报错:The AssetBundle 'xxxxx' can't be loaded because another AssetBundle with the same files is already loaded.
如果AB包已经加载过则先进行卸载:
if (myLoadedAssetBundle != null)
{
myLoadedAssetBundle.Unload(false);//关键代码
}
卸载AB包
1、卸载全部的目前没有使用的资源: Resources.UnloadUnusedAssets()
2、卸载 AssetBundle 释放其数据: AssetBundle.Unload(true/false);
3、卸载当前已加载的所有 AssetBundle: AssetBundle.UnloadAllAssetBundles(true/false)
当 为 false 时,将释放当前加载的捆绑包中的压缩文件数据,但已从捆绑包中加载的任何对象实例将保持不变。
UnloadAllAssetBundles不会中断异步加载过程,如果已经在进行异步加载了此时调用AssetBundle.UnloadAllAssetBundles,那么这个AB包还是会加载出来。
using UnityEngine;
public class AssetBundleManager : MonoBehaviour
{
public void LoadAssetBundle(string bundleName)
{
AssetBundle bundle = AssetBundle.LoadFromFile(bundleName);
if (bundle != null)
{
// 假设你有一个你想要加载的资源的名字
string assetName = "myAsset";
UnityEngine.Object asset = bundle.LoadAsset(assetName);
// 使用 asset ...
// 卸载AssetBundle
bundle.Unload(false);
// 如果确定没有其他引用,可以进一步释放内存
Resources.UnloadUnusedAssets();
System.GC.Collect();
}
}
}