using System.Collections; using System.Collections.Generic; using System.Security.Cryptography; using System.Linq; using System.IO; using UnityEngine; using UnityEditor; public class BundleHelper { static string TempPath = Application.temporaryCachePath + "/PackData"; static string TargetPath = Application.dataPath + "/StreamingAssets/PackData"; // or Application.streamingAssetsPath static string MainBundleName = "PackData"; static string MainBundle = TargetPath + "/PackData"; static string ManifestFile = Application.dataPath + "/Resources/bundles.manifest"; [MenuItem("Build/Build bundles")] public static void BuildBundles() { if(!Directory.Exists(TempPath)) Directory.CreateDirectory(TempPath); BuildAssetBundleOptions options = BuildAssetBundleOptions.None; options |= BuildAssetBundleOptions.ChunkBasedCompression; options |= BuildAssetBundleOptions.DeterministicAssetBundle; options |= BuildAssetBundleOptions.ForceRebuildAssetBundle; options |= BuildAssetBundleOptions.StrictMode; #if UNITY_IOS BuildPipeline.BuildAssetBundles(TempPath, options, BuildTarget.iOS); #elif UNITY_ANDROID BuildPipeline.BuildAssetBundles(TempPath, options, BuildTarget.Android); #else BuildPipeline.BuildAssetBundles(TempPath, options, BuildTarget.StandaloneWindows); #endif Debug.Log("Bundle生成结束"); // Move to StreamingAssets if (!Directory.Exists(TargetPath)) Directory.CreateDirectory(TargetPath); string[] files = Directory.GetFiles(TempPath, "*.*"); string dirPath = null; foreach(string file in files) { if (!file.EndsWith(".manifest") && !file.EndsWith(".meta")) { dirPath = file.Replace('\\', '/'); dirPath = dirPath.Replace(TempPath, TargetPath); if (File.Exists(dirPath)) File.Delete(dirPath); File.Move(file, dirPath); } } // 将bundle的md5写入bundles.manifest文件 AssetBundle mainBundle = AssetBundle.LoadFromFile(MainBundle); if (mainBundle != null) { AssetBundleManifest manifest = mainBundle.LoadAsset("AssetBundleManifest"); if (manifest != null) { if (File.Exists(ManifestFile)) File.Delete(ManifestFile); using (StreamWriter file = new System.IO.StreamWriter(ManifestFile, true)) { string[] bundles = manifest.GetAllAssetBundles(); List _bundles = bundles.ToList(); _bundles.Add(MainBundleName); foreach (string bundle in _bundles) { string path = TargetPath + "/" + bundle ; if (!File.Exists(path)) continue; long size = new FileInfo(path).Length; byte[] data = File.ReadAllBytes(path); string hash = FileUtil.GetMD5Hash(data); file.WriteLine(bundle + "," + size + "," + hash); } }; } mainBundle.Unload(true); } } }