1.使用依赖项的原因
- 为什么会有依赖项呢?由于公共资源(例如材质、贴图等)的使用,需要动态加载使用了这些东西的资源时,公共资源就要分成依赖项,不然会加载不出来从而丢失资源。
2.如何使用依赖包
- 当有公共资源设置成AssetBundle时,会有提示资源重复加载,需要把公共资源放到另一个包(依赖包)里面加载一次即可。
- 由于Unity会自动加载对应平台的依赖项,所以首先你得把对应平台的依赖项所在的文件夹加载到内存中。所有的依赖项数据都记录在AssetBundleManifest中,所以要把内存中的AssetBundleManifest加载出来,然后获得的所有依赖项(String类型数组)保存在数组中,遍历数组然后把每一个元素加载到内存中。最后在动态加载你需要的资源。
using System.IO; using System.Collections; using System.Collections.Generic; using UnityEngine; public class LoadPrefabs : MonoBehaviour { private void LoadDependency() { AssetBundle dependenciesAsset = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "StandaloneWindows")); AssetBundleManifest manifest = dependenciesAsset.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); string[] dependencies = manifest.GetAllDependencies("assetbundles"); foreach( string dependency in dependencies ) { AssetBundle dependencyAsyn = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "m_aienemy")); } } public void LoadPf() { LoadDependency(); AssetBundle pf_Enemy=AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath,"assetbundles")); if(pf_Enemy==null) { Debug.Log("load err"); return; } GameObject prefabs=pf_Enemy.LoadAsset<GameObject>("Pf_Enemy"); Instantiate(prefabs); } }