图集使用TexturePacker打出来的,图集用的时间旧了,不确定哪些资源是被prefab引用,哪些是不需要用的,最近查看unity工具顺便写了个简单脚本,检测图集资源被prefab引用情况
原理很简单,图集中的每个子对象在引用的时候,都是通过fileId和guid进行关联的,
guid就是图集那个png资源文件的guid,一个图集包含多个sprite,图集中的每个sprite是没有guid的,只有fileID,可以在meta文件中查看
代码要做的就是先获取到图集资源的fileId和guid,然后便利prefab所在目录下所有prefab文件,查看prefab文件中是否包含图集的guid和fileID
代码如下
public class AssetDataIfo
{
public long id;
public string name;
public Object obj;
}
[MenuItem("Assets/Atlas ReferenceViewer")]
private static void Open()
{
var selectedObject = Selection.activeObject ;
string path = AssetDatabase.GetAssetPath(selectedObject);
string GUID = AssetDatabase.AssetPathToGUID(path);
string searchFolder = "Assets/Prefab";
string[] prefabGUIDs = AssetDatabase.FindAssets("t:Prefab", new string[] { searchFolder});
foreach (var item in prefabGUIDs)
{
string itemPath = AssetDatabase.GUIDToAssetPath(item);
}
Debug.Log("select item path is " + path);
Object[] objects = AssetDatabase.LoadAllAssetsAtPath(path);
if (!path.EndsWith(".png") || objects.Length <= 1)
{
Debug.LogError("please select atlas png item");
return;
}
AssetDataIfo info;
//图集单个sprite信息字典
int index = 0;
foreach (var item in objects)
{
info = GetObjectLocalIdInFile(item);
Debug.Log(string.Format("搜索sprite:{0}的引用信息:", info.name));
EditorUtility.DisplayProgressBar("查找引用信息", info.name, index * 1.0f / objects.Length);
foreach (var prefabPath in prefabGUIDs)
{
string itemPath = AssetDatabase.GUIDToAssetPath(prefabPath);
SearchRefrence(info.id, GUID, itemPath);
}
index++;
}
EditorUtility.ClearProgressBar();
//SelectObject(objDict[id]);
}
static void SelectObject(Object selectItem)
{
Selection.activeObject = selectItem;
EditorGUIUtility.PingObject(selectItem);
}
static void SearchRefrence(long id, string guid, string prefabPath)
{
//Debug.Log("prefabPath is " + prefabPath);
string searchText = string.Format("fileID: {0}, guid: {1}",id, guid);//id.ToString();
string fullPath = Application.dataPath + prefabPath.Replace("Assets", "");
string msg = File.ReadAllText(fullPath);
int index = 0;
int count = 0;
while ((index = msg.IndexOf(searchText, index)) != -1)
{
count++;
index = index + searchText.Length;
}
if (count > 0)
Debug.Log(string.Format("\"{0}\"在prefab {1} 中出现第{2}次。", searchText, prefabPath, count));
//else Debug.Log("引用次数为0");
}