1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
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>("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<string> _bundles = bundles.ToList<string>();
_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);
}
}
}
|