using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class LoadAssetBundles : MonoBehaviour { // Use this for initialization private static LoadAssetBundles instance; private static string localFilePath; private AssetBundleManifest manifest; private static string ManifestName; void Start() { } // Update is called once per frame void Update() { } public void GetAssetBundleManifest() { AssetBundle bundle = AssetBundle.LoadFromFile(localFilePath + ManifestName); if (bundle == null) { Debug.Log("Failed to load AssetBundle!"); } else { manifest = bundle.LoadAsset("AssetBundleManifest"); bundle.Unload(false); } } public static LoadAssetBundles getInstance() { if (instance == null) { instance = new LoadAssetBundles(); localFilePath = Application.dataPath + "/AssetBundles/"; ManifestName = "AssetBundles"; } return instance; } public IEnumerator LoadAssetByName(string fileName, Action callback) where T : UnityEngine.Object { AssetManager manager=AssetManager.getInstance(); //先从资源管理器取,如果没有再从资源包中加载 if (manager.assetObject.ContainsKey(fileName)) { //Debug.Log("从资源管理器中加载了"); T obj = manager.assetObject[fileName] as T; callback(obj); } else { //Debug.Log("从资源包加载了"); if (manifest == null) { GetAssetBundleManifest(); } string[] dependencies = manifest.GetAllDependencies(fileName); AssetBundle[] dpsBundles = new AssetBundle[dependencies.Length]; for (int i = 0; i < dpsBundles.Length; i++) { string path = localFilePath + dependencies[i]; Debug.Log(path); dpsBundles[i] = AssetBundle.LoadFromFile(path); } string mainPath = localFilePath + fileName; AssetBundle mainBundle = AssetBundle.LoadFromFile(mainPath); if (mainBundle == null) { Debug.Log("Failed to load AssetBundle!"); yield return null; } T obj = mainBundle.LoadAsset(fileName); manager.assetObject.Add(fileName, obj);//加入到资源管理器 callback(obj); //yield return new WaitForSeconds(1f); mainBundle.Unload(false); for (int j = 0; j < dependencies.Length; j++) { dpsBundles[j].Unload(false); } } } public IEnumerator LoadSceneByName(string fileName, Action callback) { if (manifest == null) { GetAssetBundleManifest(); } string[] dependencies = manifest.GetAllDependencies(fileName); AssetBundle[] dpsBundles = new AssetBundle[dependencies.Length]; for (int i = 0; i < dpsBundles.Length; i++) { string path = localFilePath + dependencies[i]; dpsBundles[i] = AssetBundle.LoadFromFile(path); } string mainPath = localFilePath + fileName; AssetBundle mainBundle = AssetBundle.LoadFromFile(mainPath); if (mainBundle == null) { Debug.Log("Failed to load AssetBundle!"); yield return null; } //mainBundle.LoadAsset(fileName); callback(); yield return new WaitForSeconds(1f); mainBundle.Unload(false); for (int j = 0; j < dependencies.Length; j++) { dpsBundles[j].Unload(false); } } }