1、一般在计算资源hash的时候,需要考虑 :资源+资源meta、依赖项+依赖项meta
2、一般在计算资源hash的时候,都需要对计算结果进行加密,可以直接用C#自带的MD5进行加密
具体实现,代码如下(学习使用,结构并不完善):
1 using System; 2 using System.IO; 3 using System.Collections.Generic; 4 using UnityEditor; 5 using UnityEngine; 6 using System.Security.Cryptography; 7 using System.Text; 8 9 public class Test 10 { 11 [MenuItem("BuildTool/Lugs")] 12 static void LugsTest() 13 { 14 Debug.Log(ComputeAssetHash("Assets/UI/Prefab/ui_login/ui_login.prefab")); 15 } 16 17 static string ComputeAssetHash(string assetPath) 18 { 19 if (!File.Exists(assetPath)) 20 return null; 21 22 List<byte> list = new List<byte>(); 23 24 //读取资源及其meta文件为字节数组 25 list.AddRange(GetAssetBytes(assetPath)); 26 27 //读取资源的依赖项及其meta文件为字节数组(依赖项本质也是资源的路径) 28 string[] dependencies = AssetDatabase.GetDependencies(assetPath); 29 for (int i = 0, iMax = dependencies.Length; i < iMax; ++i) 30 list.AddRange(GetAssetBytes(dependencies[i])); 31 32 //如果资源有其他依赖项的话,也需要将其对应的字节数组读取到 list 中,然后再进行 哈希码 的计算 33 34 //返回资源 hash 35 return ComputeHash(list.ToArray()); 36 } 37 38 static byte[] GetAssetBytes(string assetPath) 39 { 40 if (!File.Exists(assetPath)) 41 return null; 42 43 List<byte> list = new List<byte>(); 44 45 var assetBytes = File.ReadAllBytes(assetPath); 46 list.AddRange(assetBytes); 47 48 string metaPath = assetPath + ".meta"; 49 var metaBytes = File.ReadAllBytes(metaPath); 50 list.AddRange(metaBytes); 51 52 return list.ToArray(); 53 } 54 55 static MD5 md5 = null; 56 static MD5 MD5 57 { 58 get 59 { 60 if (null == md5) 61 md5 = MD5.Create(); 62 return md5; 63 } 64 } 65 66 static string ComputeHash(byte[] buffer) 67 { 68 if (null == buffer || buffer.Length < 1) 69 return ""; 70 71 byte[] hash = MD5.ComputeHash(buffer); 72 StringBuilder sb = new StringBuilder(); 73 74 foreach (var b in hash) 75 sb.Append(b.ToString("x2")); 76 77 return sb.ToString(); 78 } 79 80 81 }
结果如下: