using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.SceneManagement; using Object = UnityEngine.Object; namespace ZXKFramework { public class ResAssetBundleSimple : IRes { Dictionary allAbItems = new Dictionary(); public void Load(string assetName, Action action = null) where T : Object { string tipType = typeof(T).Name; switch (tipType) { case "Sprite": break; case "AudioClip": break; case "GameObject": GameObject loObj = Load(new AssetBundleLoadData() { abName = assetName }); action?.Invoke(loObj as T); break; } } private GameObject Load(AssetBundleLoadData data) { if (!allAbItems.ContainsKey(data.abName)) { AbItem temp = new AbItem(data); allAbItems.Add(data.abName,temp); return temp.obj; } return null; } public void UnLoadAll() { foreach (var o in allAbItems.Values) { o.asset.Unload(true); if (o.obj != null) { GameObject.Destroy(o.obj); } } allAbItems.Clear(); } } public class AbItem { public AssetBundle asset { get; set; } public GameObject obj { get; set; } = null; private AssetBundleLoadData mData; public AbItem(AssetBundleLoadData data) { mData = data; string path = GetPath(data.abName); if (!File.Exists(path)) { Debug.Log("加载AB物体不存在:" + path); return; } asset = AssetBundle.LoadFromFile(path); obj = asset.LoadAsset(data.abName); asset.Unload(false); } string GetPath(string theName) { string pos = ""; #if UNITY_ANDROID pos = "Android"; #elif UNITY_IOS pos = "IOS"; #elif UNITY_EDITOR_WIN pos = "Windows"; #endif if (string.IsNullOrEmpty(mData.path)) { mData.path = Application.persistentDataPath; } string thePath = mData.path + "/Assetbundle/" + pos; if (!Directory.Exists(thePath)) Directory.CreateDirectory(thePath); thePath = thePath + "/" + theName.ToLower() + ".assetbundle"; return thePath; } } public struct AssetBundleLoadData { public string abName { get; set; } public string path { get; set; } } }