| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using UnityEngine;
- #if UNITY_EDITOR
- using UnityEditor;
- #endif
- namespace ET
- {
- [ObjectSystem]
- public class ABInfoAwakeSystem: AwakeSystem<ABInfo, string, AssetBundle>
- {
- public override void Awake(ABInfo self, string abName, AssetBundle a)
- {
- self.AssetBundle = a;
- self.Name = abName;
- self.RefCount = 1;
- }
- }
- [ObjectSystem]
- public class ABInfoDestroySystem: DestroySystem<ABInfo>
- {
- public override void Destroy(ABInfo self)
- {
- //Log.Debug($"desdroy assetbundle: {this.Name}");
- self.RefCount = 0;
- self.Name = "";
- }
- }
- public class ABInfo: Entity
- {
- public string Name
- {
- get;
- set;
- }
- public int RefCount
- {
- get;
- set;
- }
- public AssetBundle AssetBundle;
- public void Destroy(bool unload = true)
- {
- if (this.AssetBundle != null)
- {
- this.AssetBundle.Unload(unload);
- }
- this.Dispose();
- }
- }
- // 用于字符串转换,减少GC
- public static class AssetBundleHelper
- {
- public static string IntToString(this int value)
- {
- string result;
- if (ResourcesComponent.Instance.IntToStringDict.TryGetValue(value, out result))
- {
- return result;
- }
- result = value.ToString();
- ResourcesComponent.Instance.IntToStringDict[value] = result;
- return result;
- }
- public static string StringToAB(this string value)
- {
- string result;
- if (ResourcesComponent.Instance.StringToABDict.TryGetValue(value, out result))
- {
- return result;
- }
- result = value + ".unity3d";
- ResourcesComponent.Instance.StringToABDict[value] = result;
- return result;
- }
- public static string IntToAB(this int value)
- {
- return value.IntToString().StringToAB();
- }
- public static string BundleNameToLower(this string value)
- {
- string result;
- if (ResourcesComponent.Instance.BundleNameToLowerDict.TryGetValue(value, out result))
- {
- return result;
- }
- result = value.ToLower();
- ResourcesComponent.Instance.BundleNameToLowerDict[value] = result;
- return result;
- }
- }
- [ObjectSystem]
- public class ResourcesComponentAwakeSystem: AwakeSystem<ResourcesComponent>
- {
- public override void Awake(ResourcesComponent self)
- {
- self.Awake();
- }
- }
- public class ResourcesComponent: Entity
- {
- public static ResourcesComponent Instance
- {
- get;
- set;
- }
- public AssetBundleManifest AssetBundleManifestObject
- {
- get;
- set;
- }
-
- public Dictionary<int, string> IntToStringDict = new Dictionary<int, string>();
- public Dictionary<string, string> StringToABDict = new Dictionary<string, string>();
- public Dictionary<string, string> BundleNameToLowerDict = new Dictionary<string, string>() { { "StreamingAssets", "StreamingAssets" } };
- private readonly Dictionary<string, Dictionary<string, UnityEngine.Object>> resourceCache = new Dictionary<string, Dictionary<string, UnityEngine.Object>>();
- private readonly Dictionary<string, ABInfo> bundles = new Dictionary<string, ABInfo>();
- public void Awake()
- {
- Instance = this;
-
- if (Define.IsAsync)
- {
- LoadOneBundle("StreamingAssets");
- AssetBundleManifestObject = (AssetBundleManifest)GetAsset("StreamingAssets", "AssetBundleManifest");
- }
- }
- public override void Dispose()
- {
- if (this.IsDisposed)
- {
- return;
- }
- base.Dispose();
- Instance = null;
- foreach (KeyValuePair<string, ABInfo> abInfo in this.bundles)
- {
- abInfo.Value.Destroy();
- }
- this.bundles.Clear();
- this.resourceCache.Clear();
- this.IntToStringDict.Clear();
- this.StringToABDict.Clear();
- this.BundleNameToLowerDict.Clear();
- }
- private string[] GetDependencies(string assetBundleName, bool isScene = false)
- {
- string[] dependencies = new string[0];
- if (DependenciesCache.TryGetValue(assetBundleName, out dependencies))
- {
- return dependencies;
- }
- if (!Define.IsAsync)
- {
- #if UNITY_EDITOR
- if (isScene == false)
- {
- dependencies = AssetDatabase.GetAssetBundleDependencies(assetBundleName, true);
- }
- #endif
- }
- else
- {
- dependencies = this.AssetBundleManifestObject.GetAllDependencies(assetBundleName);
- }
- DependenciesCache.Add(assetBundleName, dependencies);
- return dependencies;
- }
- public string[] GetSortedDependencies(string assetBundleName, bool isScene = false)
- {
- Dictionary<string, int> info = new Dictionary<string, int>();
- List<string> parents = new List<string>();
- CollectDependencies(parents, assetBundleName, info, isScene);
- string[] ss = info.OrderBy(x => x.Value).Select(x => x.Key).ToArray();
- return ss;
- }
- private void CollectDependencies(List<string> parents, string assetBundleName, Dictionary<string, int> info, bool isScene = false)
- {
- parents.Add(assetBundleName);
- string[] deps = GetDependencies(assetBundleName, isScene);
- foreach (string parent in parents)
- {
- if (!info.ContainsKey(parent))
- {
- info[parent] = 0;
- }
- info[parent] += deps.Length;
- }
- foreach (string dep in deps)
- {
- if (parents.Contains(dep))
- {
- throw new Exception($"包有循环依赖,请重新标记: {assetBundleName} {dep}");
- }
- CollectDependencies(parents, dep, info, isScene);
- }
- parents.RemoveAt(parents.Count - 1);
- }
- // 缓存包依赖,不用每次计算
- public Dictionary<string, string[]> DependenciesCache = new Dictionary<string, string[]>();
- public bool Contains(string bundleName)
- {
- return this.bundles.ContainsKey(bundleName);
- }
- public Dictionary<string, UnityEngine.Object> GetBundleAll(string bundleName)
- {
- Dictionary<string, UnityEngine.Object> dict;
- if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
- {
- throw new Exception($"not found asset: {bundleName}");
- }
- return dict;
- }
- public UnityEngine.Object GetAsset(string bundleName, string prefab)
- {
- Dictionary<string, UnityEngine.Object> dict;
- if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
- {
- throw new Exception($"not found asset: {bundleName} {prefab}");
- }
- UnityEngine.Object resource = null;
- if (!dict.TryGetValue(prefab, out resource))
- {
- throw new Exception($"not found asset: {bundleName} {prefab}");
- }
- return resource;
- }
- public async ETTask UnloadBundles(List<string> bundleList, bool unload = true)
- {
- int i = 0;
- foreach (string bundle in bundleList)
- {
- using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, bundle.GetHashCode()))
- {
- if (++i % 5 == 0)
- {
- await TimerComponent.Instance.WaitFrameAsync();
- }
- this.UnloadBundle(bundle, unload);
- }
- }
- }
- // 只允许场景设置unload为false
- public void UnloadBundle(string assetBundleName, bool unload = true)
- {
- assetBundleName = assetBundleName.BundleNameToLower();
- string[] dependencies = GetSortedDependencies(assetBundleName);
- //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
- foreach (string dependency in dependencies)
- {
- this.UnloadOneBundle(dependency, unload);
- }
- //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
- }
- private void UnloadOneBundle(string assetBundleName, bool unload = true)
- {
- assetBundleName = assetBundleName.BundleNameToLower();
- ABInfo abInfo;
- if (!this.bundles.TryGetValue(assetBundleName, out abInfo))
- {
- return;
- }
- //Log.Debug($"---------------unload one bundle {assetBundleName} refcount: {abInfo.RefCount - 1}");
- --abInfo.RefCount;
- if (abInfo.RefCount > 0)
- {
- return;
- }
-
- //Log.Debug($"---------------truly unload one bundle {assetBundleName} refcount: {abInfo.RefCount}");
- this.bundles.Remove(assetBundleName);
- this.resourceCache.Remove(assetBundleName);
- abInfo.Destroy(unload);
- // Log.Debug($"cache count: {this.cacheDictionary.Count}");
- }
- /// <summary>
- /// 同步加载assetbundle
- /// </summary>
- /// <param name="assetBundleName"></param>
- /// <returns></returns>
- public void LoadBundle(string assetBundleName)
- {
- assetBundleName = assetBundleName.ToLower();
- string[] dependencies = GetSortedDependencies(assetBundleName);
- //Log.Debug($"-----------dep load start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
- foreach (string dependency in dependencies)
- {
- if (string.IsNullOrEmpty(dependency))
- {
- continue;
- }
- this.LoadOneBundle(dependency);
- }
- //Log.Debug($"-----------dep load finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
- }
- public void AddResource(string bundleName, string assetName, UnityEngine.Object resource)
- {
- Dictionary<string, UnityEngine.Object> dict;
- if (!this.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
- {
- dict = new Dictionary<string, UnityEngine.Object>();
- this.resourceCache[bundleName] = dict;
- }
- dict[assetName] = resource;
- }
- private void LoadOneBundle(string assetBundleName)
- {
- assetBundleName = assetBundleName.BundleNameToLower();
- ABInfo abInfo;
- if (this.bundles.TryGetValue(assetBundleName, out abInfo))
- {
- ++abInfo.RefCount;
- //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
- return;
- }
-
- if (!Define.IsAsync)
- {
- string[] realPath = null;
- #if UNITY_EDITOR
- realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
- foreach (string s in realPath)
- {
- string assetName = Path.GetFileNameWithoutExtension(s);
- UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
- AddResource(assetBundleName, assetName, resource);
- }
-
-
- if (realPath.Length > 0)
- {
- abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
- this.bundles[assetBundleName] = abInfo;
- //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
- }
- else
- {
- Log.Error($"assets bundle not found: {assetBundleName}");
- }
- #endif
- return;
- }
- string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
- AssetBundle assetBundle = null;
- if (File.Exists(p))
- {
- assetBundle = AssetBundle.LoadFromFile(p);
- }
- else
- {
- p = Path.Combine(PathHelper.AppResPath, assetBundleName);
- assetBundle = AssetBundle.LoadFromFile(p);
- }
- if (assetBundle == null)
- {
- // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
- Log.Warning($"assets bundle not found: {assetBundleName}");
- return;
- }
- if (!assetBundle.isStreamedSceneAssetBundle)
- {
- // 异步load资源到内存cache住
- UnityEngine.Object[] assets = assetBundle.LoadAllAssets();
- foreach (UnityEngine.Object asset in assets)
- {
- AddResource(assetBundleName, asset.name, asset);
- }
- }
- abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
- this.bundles[assetBundleName] = abInfo;
-
- //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
- }
- /// <summary>
- /// 异步加载assetbundle
- /// </summary>
- /// <param name="assetBundleName"></param>
- /// <param name="isScene"></param>
- /// <returns></returns>
- public async ETTask LoadBundleAsync(string assetBundleName, bool isScene = false)
- {
- assetBundleName = assetBundleName.BundleNameToLower();
-
- string[] dependencies = GetSortedDependencies(assetBundleName);
- //Log.Debug($"-----------dep load async start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
- using var tasts = ListComponent<ETTask>.Create();
- async ETTask loadDependency(string dependency)
- {
- using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode()))
- {
- await this.LoadOneBundleAsync(dependency, isScene);
- }
- }
- foreach (string dependency in dependencies)
- {
- if (string.IsNullOrEmpty(dependency))
- {
- continue;
- }
- tasts.List.Add(loadDependency(dependency));
- }
- await ETTaskHelper.WaitAll(tasts.List);
- }
-
- private async ETTask LoadOneBundleAsync(string assetBundleName, bool isScene)
- {
- assetBundleName = assetBundleName.BundleNameToLower();
- ABInfo abInfo;
- if (this.bundles.TryGetValue(assetBundleName, out abInfo))
- {
- ++abInfo.RefCount;
- //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
- return;
- }
- string p = "";
- AssetBundle assetBundle = null;
-
- if (!Define.IsAsync)
- {
- #if UNITY_EDITOR
- if (isScene)
- {
- p = Path.Combine(Application.dataPath, "../SceneBundle/", assetBundleName);
- if (File.Exists(p)) // 如果场景有预先打包
- {
- using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.CreateWithParent<AssetsBundleLoaderAsync>(this))
- {
- assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
- }
- if (assetBundle == null)
- {
- // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
- Log.Warning($"Scene bundle not found: {assetBundleName}");
- return;
- }
-
- abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
- this.bundles[assetBundleName] = abInfo;
- }
- }
- else
- {
- string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
- foreach (string s in realPath)
- {
- string assetName = Path.GetFileNameWithoutExtension(s);
- UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
- AddResource(assetBundleName, assetName, resource);
- }
- if (realPath.Length > 0)
- {
- abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
- this.bundles[assetBundleName] = abInfo;
- //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
- }
- else
- {
- Log.Error("Bundle not exist! BundleName: " + assetBundleName);
- }
- }
- // 编辑器模式也不能同步加载
- await TimerComponent.Instance.WaitAsync(20);
- #endif
- return;
- }
-
- p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
- if (!File.Exists(p))
- {
- p = Path.Combine(PathHelper.AppResPath, assetBundleName);
- }
- if (!File.Exists(p))
- {
- Log.Error("Async load bundle not exist! BundleName : " + p);
- return;
- }
- using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.CreateWithParent<AssetsBundleLoaderAsync>(this))
- {
- assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
- }
- if (assetBundle == null)
- {
- // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
- Log.Warning($"assets bundle not found: {assetBundleName}");
- return;
- }
- if (!assetBundle.isStreamedSceneAssetBundle)
- {
- // 异步load资源到内存cache住
- UnityEngine.Object[] assets;
- using (AssetsLoaderAsync assetsLoaderAsync = EntityFactory.CreateWithParent<AssetsLoaderAsync, AssetBundle>(this, assetBundle))
- {
- assets = await assetsLoaderAsync.LoadAllAssetsAsync();
- }
- foreach (UnityEngine.Object asset in assets)
- {
- AddResource(assetBundleName, asset.name, asset);
- }
- }
- abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
- this.bundles[assetBundleName] = abInfo;
-
- //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
- }
- public string DebugString()
- {
- StringBuilder sb = new StringBuilder();
- foreach (ABInfo abInfo in this.bundles.Values)
- {
- sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
- }
- return sb.ToString();
- }
- }
- }
|