位置:包体内的AssetBundle只能放在StreamingAssets文件下,别的目录是无法读取哦
加载函数:
(1)AssetBundle.LoadFromFile()
同步加载
(2)AssetBundle.LoadFromFileAsync()
异步加载
特别注意:加载AssetBundle之前,需要使用AssetBundleManifest文件提取每个AssetBundle的依赖关系。
处理依赖关系的函数:manifest.GetAllDependencies(),来获取AssetBundle的依赖关系。
加载普通资源
下面是一个小例子:
主要流程如下:
1.0 获取StreamingAssets(Bundle资源)
2.0 获取依赖关系文件AssetBundleManifest
3.0 加载依赖的资源
4.0 加载Bundle
5.0 从Bundle中读取对应的资源
6.0 进行实例化
void Start () {
//获取到StreamingAssets
AssetBundle assetBundle =
AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath,
"StreamingAssets"));
//加载Manifest文件
AssetBundleManifest assetBundleManifest =
assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
//在加载Assetbundle之前需要先加载依赖bundle
foreach (var item in assetBundleManifest.GetAllDependencies("cube"))
{
AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath,
item));
}
//读取Bundle(读取所需要的Bundle)
assetBundle =
AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath,"cube"));//传入路径和资源名称(不需要后缀)
//从Bundle中读取资源
GameObject prefab = assetBundle.LoadAsset<GameObject>("Cube");
//实例化
GameObject.Instantiate<GameObject>(prefab);
}
加载场景
我们在Bundle中加载场景资源是不需要在Scenes In Build中添加这个资源
使用的函数:
AssetBundle.LoadFromFile()加载场景,接着读取场景即可。
string path = Path.Combine(Application.streamingAssetsPath,"scene");//打包的资源名
AssetBundle assetBundle = AssetBundle.LoadFromFile(path);//加载场景
if (assetBundle != null)
{
SceneManager.LoadScene("SceneBundle");//读取场景
}
else
{
Debug.LogFormat("场景资源加载失败!");
}