Tanoda
AssetBundleManagerHelper.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Linq;
4using System.Reflection;
5using UnityEngine;
6
8{
9 internal static class AssetBundleManagerHelper
10 {
11 private static readonly IDictionary _abCacheManifestDic;
12 private static readonly MethodInfo _abCacheUnloadMethod;
13
14 static AssetBundleManagerHelper()
15 {
16 var abmType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypesSafe()).FirstOrDefault(x => x.Name == "AssetBundleManager");
17 if (abmType != null)
18 {
19 // public static Dictionary<string, AssetBundleManager.BundlePack> ManifestBundlePack {get;}
20 var mbpProp = abmType.GetProperty("ManifestBundlePack", BindingFlags.Static | BindingFlags.Public);
21 _abCacheManifestDic = mbpProp != null ? mbpProp.GetValue(null, null) as IDictionary : null;
22
23 if (_abCacheManifestDic != null)
24 {
25 // public static void UnloadAssetBundle(string assetBundleName, bool isUnloadForceRefCount, string manifestAssetBundleName = null, bool unloadAllLoadedObjects = false)
26 _abCacheUnloadMethod = abmType.GetMethod("UnloadAssetBundle", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string), typeof(bool), typeof(string), typeof(bool) }, null);
27 }
28 }
29 }
30
31 public static void DrawButtonIfAvailable()
32 {
33 if (_abCacheUnloadMethod != null && GUILayout.Button("Clear AssetBundle Cache"))
34 {
35 try
36 {
37 var unloadedCount = ClearAssetBundleCache();
38 RuntimeUnityEditorCore.Logger.Log(LogLevel.Message, "Unloaded " + unloadedCount + " AssetBundles");
39 }
40 catch (Exception e)
41 {
42 RuntimeUnityEditorCore.Logger.Log(LogLevel.Message | LogLevel.Error, "Failed to clear the AssetBundle cache - " + e);
43 }
44 }
45 }
46
47 private static int ClearAssetBundleCache()
48 {
49 var unloadedCount = 0;
50
51 var manifestDicEnumerator = _abCacheManifestDic.GetEnumerator();
52 while (manifestDicEnumerator.MoveNext())
53 {
54 var valueType = manifestDicEnumerator.Value.GetType();
55 // public Dictionary<string, LoadedAssetBundle> LoadedAssetBundles {get; set;}
56 var loadedBundlesProp = valueType.GetProperty("LoadedAssetBundles", BindingFlags.Instance | BindingFlags.Public);
57 var loadedBundlesDic = loadedBundlesProp != null ? loadedBundlesProp.GetValue(manifestDicEnumerator.Value, null) as IDictionary : null;
58
59 if (loadedBundlesDic == null) throw new InvalidOperationException("Failed to get LoadedAssetBundles dictionary");
60
61 // Need a copy of keys because unloading removes them
62 foreach (var labsKey in loadedBundlesDic.Keys.Cast<string>().ToList())
63 {
64 _abCacheUnloadMethod.Invoke(null, new[] { labsKey, true, manifestDicEnumerator.Key, false });
65 unloadedCount++;
66 }
67 }
68
69 return unloadedCount;
70 }
71 }
72}
void Log(LogLevel logLogLevel, object content)