SAssetsBundleHelper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. namespace SFramework.Editor
  6. {
  7. public static class SAssetsBundleHelper
  8. {
  9. static string ResourcesBuildDir
  10. {
  11. get
  12. {
  13. var dir = "Assets/" + SFrameworkDef.ResourceDir + "/";
  14. return dir;
  15. }
  16. }
  17. /// <summary>
  18. /// Unity 5新AssetBundle系统,需要为打包的AssetBundle配置名称
  19. ///
  20. /// 直接将KEngine配置的BundleResources目录整个自动配置名称,因为这个目录本来就是整个导出
  21. /// </summary>
  22. [MenuItem("SFramework/AssetBundle/Auto Set Names To [BundleResources]")]
  23. public static void AutoSetAssetBundleNames()
  24. {
  25. var dir = ResourcesBuildDir;
  26. // Check marked asset bundle whether real
  27. foreach (var assetGuid in AssetDatabase.FindAssets(""))
  28. {
  29. var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);
  30. var assetImporter = AssetImporter.GetAtPath(assetPath);
  31. var bundleName = assetImporter.assetBundleName;
  32. if (string.IsNullOrEmpty(bundleName))
  33. {
  34. continue;
  35. }
  36. if (!assetPath.StartsWith(dir))
  37. {
  38. assetImporter.assetBundleName = null;
  39. }
  40. }
  41. // set BundleResources's all bundle name
  42. foreach (var filepath in System.IO.Directory.GetFiles(dir, "*.*", System.IO.SearchOption.AllDirectories))
  43. {
  44. if (filepath.EndsWith(".meta")) continue;
  45. var importer = AssetImporter.GetAtPath(filepath);
  46. if (importer == null)
  47. {
  48. Debug.LogError(string.Format("Not found: {0}", filepath));
  49. continue;
  50. }
  51. var bundleName = filepath.Substring(dir.Length, filepath.Length - dir.Length);
  52. importer.assetBundleName = bundleName + SFrameworkDef.AssetsBundleExtName;
  53. }
  54. Debug.Log("Make all asset name success!");
  55. }
  56. /// <summary>
  57. /// 清理冗余,即无此资源,却存在AssetBundle的文件, Unity 5 only
  58. /// </summary>
  59. [MenuItem("SFramework/AssetBundle/Clean Redundancies")]
  60. public static void CleanAssetBundlesRedundancies()
  61. {
  62. var platformName = SPlatformInfo.GetBuildPlatformName();
  63. var outputPath = GetExportPath(EditorUserBuildSettings.activeBuildTarget);
  64. var srcList = new List<string>(System.IO.Directory.GetFiles(ResourcesBuildDir, "*.*", System.IO.SearchOption.AllDirectories));
  65. for (var i = srcList.Count - 1; i >= 0; i--)
  66. {
  67. if (srcList[i].EndsWith(".meta"))
  68. srcList.RemoveAt(i);
  69. else
  70. srcList[i] = srcList[i].Replace(ResourcesBuildDir, "").ToLower();
  71. }
  72. var toListMap = new Dictionary<string, string>();
  73. var toList = new List<string>(System.IO.Directory.GetFiles(outputPath, "*.*", System.IO.SearchOption.AllDirectories));
  74. for (var i = toList.Count - 1; i >= 0; i--)
  75. {
  76. var filePath = toList[i];
  77. if (toList[i].EndsWith((".meta")) || toList[i].EndsWith(".manifest"))
  78. {
  79. toList.RemoveAt(i);
  80. }
  81. else
  82. {
  83. var rName = toList[i].Replace(outputPath, "");
  84. if (rName == platformName || // 排除AB 平台总索引文件,
  85. rName == (platformName + ".manifest") ||
  86. rName == (platformName + ".meta") ||
  87. rName == (platformName + ".manifest.meta"))
  88. {
  89. toList.RemoveAt(i);
  90. }
  91. else
  92. {
  93. // 去掉扩展名,因为AssetBundle额外扩展名
  94. toList[i] = System.IO.Path.ChangeExtension(rName, "");// 会留下最后句点
  95. toList[i] = toList[i].Substring(0, toList[i].Length - 1); // 去掉句点
  96. toListMap[toList[i]] = filePath;
  97. }
  98. }
  99. }
  100. // 删文件和manifest
  101. for (var i = 0; i < toList.Count; i++)
  102. {
  103. if (!srcList.Contains(toList[i]))
  104. {
  105. var filePath = toListMap[toList[i]];
  106. var manifestPath = filePath + ".manifest";
  107. System.IO.File.Delete(filePath);
  108. Debug.LogWarning("Delete... " + filePath);
  109. if (System.IO.File.Exists(manifestPath))
  110. {
  111. System.IO.File.Delete(manifestPath);
  112. Debug.LogWarning("Delete... " + manifestPath);
  113. }
  114. }
  115. }
  116. }
  117. [MenuItem("SFramework/AssetBundle/Create Version File")]
  118. public static void CreateVersionFile()
  119. {
  120. AssetBundle.UnloadAllAssetBundles(true);
  121. var platformName = SPlatformInfo.GetBuildPlatformName();
  122. var outputPath = GetExportPath(EditorUserBuildSettings.activeBuildTarget);
  123. Debug.Log(string.Format("CreateVersionFile -> platformName:{0} outputPath:{1}", platformName, outputPath));
  124. // Load manifestAB
  125. string manifestABPath = Application.dataPath + "/../Product/Bundles/" + platformName + "/" + platformName;
  126. Debug.Log("manifestABPath -> " + manifestABPath);
  127. byte[] byManifest = System.IO.File.ReadAllBytes(manifestABPath);
  128. AssetBundle manifestAB = AssetBundle.LoadFromMemory(byManifest);
  129. if (manifestAB == null)
  130. {
  131. Debug.LogError("CreateVersionFile -> Get ManifestAB Failed. Path:" + manifestABPath);
  132. return;
  133. }
  134. AssetBundleManifest manifest = manifestAB.LoadAsset("AssetBundleManifest") as AssetBundleManifest;
  135. if (manifest == null)
  136. {
  137. Debug.LogError("CreateVersionFile -> Get Manifest From AssetBundle Failed.");
  138. return;
  139. }
  140. SVersionInfo curVersionInfo = new SVersionInfo();
  141. curVersionInfo.version = 0;
  142. curVersionInfo.fileInfo = new List<SFileInfo>();
  143. // Add Manifest File
  144. string manifestFileName = platformName;
  145. SFileInfo manifestFileInfo = SToolFunction.CreateFileInfo(manifestFileName, outputPath + manifestFileName);
  146. curVersionInfo.fileInfo.Add(manifestFileInfo);
  147. // Add Manifest Ext File(platform.manifest)
  148. string manifestExtFileName = platformName + ".manifest";
  149. SFileInfo manifestExtFileInfo = SToolFunction.CreateFileInfo(manifestExtFileName, outputPath + manifestExtFileName);
  150. curVersionInfo.fileInfo.Add(manifestExtFileInfo);
  151. // Add files in manifest.
  152. string[] allABName = manifest.GetAllAssetBundles();
  153. curVersionInfo.fileCount = allABName.Length;
  154. foreach (string abName in allABName)
  155. {
  156. string oneABFullPathWithName = outputPath + abName;
  157. SFileInfo curFileInfo = SToolFunction.CreateFileInfo(abName, oneABFullPathWithName);
  158. curFileInfo.hashInfo = manifest.GetAssetBundleHash(abName).ToString();
  159. curVersionInfo.fileInfo.Add(curFileInfo);
  160. // Debug.Log(string.Format("oneAB:{0} Size:{1}", abName, oneABFileInfo.Length));
  161. Debug.Log(string.Format("abName: {0} FileSize:{1} HashCode: {2}",
  162. curFileInfo.fileName, curFileInfo.fileSize, curFileInfo.hashInfo));
  163. }
  164. string jsonString = LitJson.JsonMapper.ToJson(curVersionInfo);
  165. Debug.Log("jsonString -> " + jsonString);
  166. string jsonPath = Application.dataPath + "/../Product/Bundles/" + platformName + "/" + SFrameworkDef.VersionFileName;
  167. System.IO.StreamWriter build_info = new System.IO.StreamWriter(jsonPath);
  168. build_info.Write(jsonString);
  169. build_info.Close();
  170. build_info.Dispose();
  171. manifestAB.Unload(true);
  172. Debug.Log("CreateVersionFile Success!");
  173. }
  174. //[MenuItem("SFramework/AssetBundle/Build All to All Platforms")]
  175. //public static void BuildAllAssetBundlesToAllPlatforms()
  176. //{
  177. // var platforms = new List<BuildTarget>()
  178. // {
  179. // BuildTarget.iOS,
  180. // BuildTarget.Android,
  181. // BuildTarget.StandaloneWindows,
  182. // BuildTarget.StandaloneOSX,
  183. // };
  184. // // Build all support platforms asset bundle
  185. // var currentBuildTarget = EditorUserBuildSettings.activeBuildTarget;
  186. // platforms.Remove(currentBuildTarget);
  187. // BuildAllAssetBundles();
  188. // foreach (var platform in platforms)
  189. // {
  190. // if (EditorUserBuildSettings.SwitchActiveBuildTarget(platform))
  191. // BuildAllAssetBundles();
  192. // }
  193. // // revert platform
  194. // EditorUserBuildSettings.SwitchActiveBuildTarget(currentBuildTarget);
  195. //}
  196. [MenuItem("SFramework/AssetBundle/ReBuild All")]
  197. public static void ReBuildAllAssetBundles()
  198. {
  199. var outputPath = GetExportPath(EditorUserBuildSettings.activeBuildTarget);
  200. System.IO.Directory.Delete(outputPath, true);
  201. Debug.Log("Delete folder: " + outputPath);
  202. BuildAllAssetBundles();
  203. }
  204. [MenuItem("SFramework/AssetBundle/Build All %&b")]
  205. public static void BuildAllAssetBundles()
  206. {
  207. if (EditorApplication.isPlaying)
  208. {
  209. Debug.LogError("Cannot build in playing mode! Please stop!");
  210. return;
  211. }
  212. AutoSetAssetBundleNames();
  213. var outputPath = GetExportPath(EditorUserBuildSettings.activeBuildTarget);
  214. Debug.Log(string.Format("Asset bundle start build to: {0}", outputPath));
  215. BuildPipeline.BuildAssetBundles(outputPath, BuildAssetBundleOptions.DeterministicAssetBundle, EditorUserBuildSettings.activeBuildTarget);
  216. //BuildPipeline.BuildAssetBundles(outputPath, BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.AppendHashToAssetBundleName, EditorUserBuildSettings.activeBuildTarget);
  217. CreateVersionFile();
  218. }
  219. /// <summary>
  220. /// Extra Flag -> ex: Android/ AndroidSD/ AndroidHD/
  221. /// </summary>
  222. /// <param name="platfrom"></param>
  223. /// <returns></returns>
  224. public static string GetExportPath(BuildTarget platfrom)
  225. {
  226. //string basePath =
  227. // System.IO.Path.GetFullPath(KEngine.AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleBuildRelPath));
  228. string basePath = SFrameworkDef.AssetsBundleProductDir;
  229. if (System.IO.File.Exists(basePath))
  230. {
  231. SAssetsBundleHelper.ShowDialog("路径配置错误: " + basePath);
  232. throw new System.Exception("路径配置错误");
  233. }
  234. if (!System.IO.Directory.Exists(basePath))
  235. {
  236. System.IO.Directory.CreateDirectory(basePath);
  237. }
  238. string path = null;
  239. var platformName = SPlatformInfo.GetBuildPlatformName();
  240. path = basePath + "/" + platformName + "/";
  241. if (!System.IO.Directory.Exists(path))
  242. {
  243. System.IO.Directory.CreateDirectory(path);
  244. }
  245. return path;
  246. }
  247. public static void ClearConsole()
  248. {
  249. System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SceneView));
  250. System.Type type = assembly.GetType("UnityEditorInternal.LogEntries");
  251. System.Reflection.MethodInfo method = type.GetMethod("Clear");
  252. method.Invoke(null, null);
  253. }
  254. public static bool ShowDialog(string msg, string title = "提示", string button = "确定")
  255. {
  256. return EditorUtility.DisplayDialog(title, msg, button);
  257. }
  258. public static void ShowDialogSelection(string msg, System.Action yesCallback)
  259. {
  260. if (EditorUtility.DisplayDialog("确定吗", msg, "是!", "不!"))
  261. {
  262. yesCallback();
  263. }
  264. }
  265. }
  266. }