[Unity]扫描项目中无效的Prefab

2019/11 01 21:11

如果Prefab含有丢失的Prefab,在打AssetBundles时,Unity有机率Creash,所以添加工具加以检测

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public static class EditorMissingPrefabScanTool
{
    static public void CheckMissingPrefab(string assetPath, GameObject go, ref HashSet<string> output)
    {
        if (go.name.Contains("Missing Prefab"))
        {
            output.Add(string.Format("{0} 含有无效的Prefab\n", assetPath));
            return;
        }

        for(int i=0; i<go.transform.childCount; ++i)
        {
            CheckMissingPrefab( assetPath, go.transform.GetChild(i).gameObject, ref output);
        }
    }

    static public string GetMissingPrefabLog()
    {
        HashSet<string> allLog = new HashSet<string>();
        System.Text.StringBuilder slog = new System.Text.StringBuilder();
        var allPrefabFiles = System.IO.Directory.GetFiles("Assets/", "*.prefab", System.IO.SearchOption.AllDirectories);
        for(int i=0; i<allPrefabFiles.Length; ++i)
        {
            EditorUtility.DisplayProgressBar("扫描", string.Format("正在扫描{0}/{1}", i, allPrefabFiles.Length), 
                (float)i / allPrefabFiles.Length);
            var prefabFilename = allPrefabFiles[i];
            var go = AssetDatabase.LoadAssetAtPath<GameObject>(prefabFilename);
            CheckMissingPrefab(prefabFilename, go, ref allLog);
        }
        EditorUtility.ClearProgressBar();

        foreach(var str in allLog)
        {
            slog.Append(str);
        }
        return slog.ToString();
    }

    [MenuItem("Tool/扫描无效Prefab")]
    static public void Tool()
    {
        var str = GetMissingPrefabLog();
        if (str.Length > 0)
        {
            Log.Error(str);
            EditorUtility.DisplayDialog("结果", "扫描到异常Prefab,请查看Console", "OK");
        }
        else
        {
            EditorUtility.DisplayDialog("结果", "所有Prefab均正常", "OK");
        }
    }
}