unity在資源打包的時候,關於 hash 計算的簡單總結


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 }

結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM