本次实验中,我检查的是项目中的哪些贴图是否被重用。代码如下:
首先,就是MD5码的生成,这个是最重要的:
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class FileHelper{
public static string MD5Stream(Stream inputStream){
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
md5.ComputeHash(inputStream);
byte[] bt = md5.Hash;
StringBuilder sb = new StringBuilder();
for(int i =0;i < bt.Length; i++){
sb.Append(bt[i].ToString("X2"));
}
return sb.ToString();
}
public static string MD5Stream(string filePath){
try{
using(FileStream stream = File.Open(filePath,FileMode.Open)){
return MD5Stream(stream);
}
}
catch(System.Exception e){
Debug.Log("抛出异常:" + e);
return;
}
}
}
然后我们只需要提供需要检查资源的路径就可以了。
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
public class MD5Test:Editor{
private static Dictionary<string, List<string>> ;
private static List<string> listPaths;
[MenuItem("MD5/SearchTexture")]
public static void SearchAllTexture(){
dics = new Dictionary<string,List<string>>();
listPaths = new List<string>();
string[] guids = AssetDatabase.FindAssets("t:" + "Texture2D",new string[]{"Assets"});
for(int i =0;i<guids.Length;i++){
string texturePath = AssetDatabase.GUIDToAssetPath(guids[i]);
string code = FileHelper.MD5Stream(texturePath);
listPaths.clear();
if(!dics.ContainsKey(ecode)){
listPaths.Add(texturePath);
dics.Add(ecode,listPaths);
}
else
{
dics[ecode].Add(listPaths);
}
}
}
}
这样的话,我们就获得了所有的Texture2D的MD5码。