A brief summary of hash calculation in resource packaging of unity

1. Generally, when calculating resource hash, we need to consider: resource + resource meta, dependency + dependency meta

2. Generally, when computing resource hash, the calculation results need to be encrypted, which can be directly encrypted with MD5 of C #

Specific implementation, the code is as follows (learning to use, structure is not perfect):

 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         //Read the resource and its meta file as an array of bytes
25 list.AddRange(GetAssetBytes(assetPath));
26 
27         // Read the resource's dependencies and its meta file as an array of bytes (dependencies are essentially paths to the resource as well)
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         //If the resource has other dependencies, the corresponding byte array should also be read into the list, and then the hash code should be calculated
33 
34         //return the resource 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 }

The following results are:

Similar Posts: