Unity 按需筛选特定资源

有的美术同学为了方便会找一些现有的不符合规范的资源,久而久之就会混进来一些中文,空格,大尺寸贴图等.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using Object = UnityEngine.Object;
public static class AssetCheckTools
{
    //- {fileID: 10308, guid: 0000000000000000f000000000000000, type: 0} => - {fileID: 2100000, guid: 1fa347f931a5a55428d07a9b9d1fbb54, type: 2} //粒子特效

    //m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} => m_Sprite: {fileID: 21300000, guid: 8f18e2f2029b84d4eadb84e4cddf833d, type: 3} //UISP;
    //m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} => m_Sprite: {fileID: 21300000, guid: 8f18e2f2029b84d4eadb84e4cddf833d, type: 3} //Background;
    //m_Sprite: {fileID: 10917, guid: 0000000000000000f000000000000000, type: 0} //UIMask
    //m_Sprite: {fileID: 10901, guid: 0000000000000000f000000000000000, type: 0} //Checkmark
    //m_Sprite: {fileID: 10913, guid: 0000000000000000f000000000000000, type: 0} //knob 
    //m_Sprite: {fileID: 10911, guid: 0000000000000000f000000000000000, type: 0} Input
    //

    [UnityEditor.MenuItem("AssetTools/IosImgSet")]
    public static void IosImgSet()
    {
        AssetDatabase.FindAssets("t:texture2D", new string[] { "Assets" })
            .Select(guid =>
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                return AssetImporter.GetAtPath(path) as TextureImporter;

            }).
            ForEach(imp =>
            {
                if (imp != null)
                {
                    var set = imp.GetPlatformTextureSettings(IPhonePlatform);
                    set.format = TextureImporterFormat.ASTC_10x10;
                    imp.SetPlatformTextureSettings(set);
                    imp.SaveAndReimport();
                }
            });
    }

    [UnityEditor.MenuItem("AssetTools/FBX")]
    public static void FBX()
    {
        AssetDatabase.FindAssets("t:Model", new string[] { "Assets" })
            .Select(guid =>
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                return AssetImporter.GetAtPath(path) as ModelImporter;

            }).
            ForEach(imp =>
            {
                if (imp != null && imp.materialImportMode != ModelImporterMaterialImportMode.None)
                {
                    imp.materialImportMode = ModelImporterMaterialImportMode.None;
                    imp.SaveAndReimport(); 
                }
            });
    }

    [UnityEditor.MenuItem("AssetTools/Material")]
    public static void Material()
    {
        var qu = AssetDatabase.FindAssets("t:Material", new string[] { "Assets" })
            .Select(guid => AssetDatabase.GUIDToAssetPath(guid))
            .Where(path =>
            {
                var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
                if (mat == null)
                    return false;
                if (mat.shader.name.Contains("Default_Standard"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });

        Debug.LogError(qu.Count());

        var set = qu.Where(path => !Microsoft.MixedReality.Toolkit.Utilities.Editor.DependencyWindow.UnList.Add(path));
        Debug.LogError(set.Count()) ;

        set.ForEach(path =>
        {
            FileUtil.DeleteFileOrDirectory(path);
        });
        //.Where(path => !Microsoft.MixedReality.Toolkit.Utilities.Editor.DependencyWindow.UnList.Add(path))
        //.ForEach(path => {
        //    var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
        //    Debug.LogError(mat.shader.name, mat);
        //});
    }

    [UnityEditor.MenuItem("AssetTools/Ab")]
    public static void AB()
    {
        var all = AssetDatabase.FindAssets("", new string[] { "Assets" })
             .Select(guid => AssetDatabase.GUIDToAssetPath(guid))
             .Where(path => path.Contains(" "))
             .Distinct();
        File.WriteAllLines(@"C:\Users\admin\Desktop\新建文件夹 (2)\存在空格的资源", all);
        //    .ForEach(Debug.LogError);

        all = AssetDatabase.FindAssets("", new string[] { "Assets/Art" })
            .SelectMany(guid => AssetDatabase.GetDependencies(AssetDatabase.GUIDToAssetPath(guid), true))
            .Distinct()
            .Where(path => !path.Contains("Assets/Art") && !path.EndsWith(".cs"));

        File.WriteAllLines(@"C:\Users\admin\Desktop\新建文件夹 (2)\存在引用未在Art目录的资源", all);

        all = AssetDatabase.FindAssets("t:Material", new string[] { "Assets" })
            .SelectMany(guid => AssetDatabase.GetDependencies(AssetDatabase.GUIDToAssetPath(guid), true))
            .Where(path => !path.EndsWith(".cs"))
            .Where(path => AssetDatabase.LoadAssetAtPath<Sprite>(path) != null)
            .Distinct();
        File.WriteAllLines(@"C:\Users\admin\Desktop\新建文件夹 (2)\Material使用了开启Sprite的贴图", all);

    }
    private static void ForEach<T>(this IEnumerable<T> collection,Action<T> action)
    {
        foreach (var item in collection)
        {
            action(item);
        }
    }
    [UnityEditor.MenuItem("AssetTools/Shader")]
    public static void Mat()
    {
        var m = AssetDatabase.LoadAssetAtPath<Material>("Assets/DefaultResources/Default-ParticleSystem.mat");

        Debug.LogError(m);

        AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets" })
             .Select(guid => AssetDatabase.LoadAssetAtPath<GameObject>(AssetDatabase.GUIDToAssetPath(guid)))
             .Where(go=>
             {
                 var flag = false;
                 var pas = go.GetComponentsInChildren<ParticleSystem>(true);
                 
                 foreach (var pa in pas)
                 {
                     var renderer = pa.GetComponent<Renderer>();
                     if (renderer != null && renderer.sharedMaterial!=null && renderer.sharedMaterial.shader.name.Contains("Particles/Standard"))
                     {
                         renderer.material = m;
                         Debug.LogError(AssetDatabase.GetAssetPath(renderer.sharedMaterial));
                         flag = true;
                     }
                 }
                 return flag;
             })
             .ForEach(go=> EditorUtility.SetDirty(go));

    }

    [UnityEditor.MenuItem("AssetTools/In")]
    public static void MatShader()
    {
        //AssetDatabase.FindAssets("t:Material", new string[] { "Assets" })
        //    .Select(guid => AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(guid)))
        //    .Where(mat => mat.shader.name.Contains("Particles/Standard"))
        //    .ForEach(mat=>Debug.LogError(mat, mat));
        var UnityAssets = AssetDatabase.LoadAllAssetsAtPath("Resources/unity_builtin_extra");
        foreach (var asset in UnityAssets)
        {
            Debug.Log(asset.GetType()+">>>"+asset.name);
            if(asset.GetType()==typeof(Material))
            {
                AssetDatabase.CreateAsset(UnityEngine.Object.Instantiate(asset), $"Assets/DefaultResources/{asset.name}.mat");
                AssetDatabase.Refresh();
            }
            if (asset.GetType() == typeof(Texture2D))
            {
                var t2d = UnityEngine.Object.Instantiate(asset) as Texture2D;
                
            }
        }
    }


    [UnityEditor.MenuItem("AssetTools/材质属性无效属性检测")]
    public static void MatFind()
    {
        AssetDatabase.FindAssets("t:Material", new string[] { "Assets" })
            .Select(guid => AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(guid)))
            .ForEach(mat =>
            {
                SerializedObject so = new SerializedObject(mat);
                SerializedProperty m_SavedProperties = so.FindProperty("m_SavedProperties");
                SerializedProperty m_TexEnvs = m_SavedProperties.FindPropertyRelative("m_TexEnvs");
                SerializedProperty m_Floats = m_SavedProperties.FindPropertyRelative("m_Floats");
                SerializedProperty m_Colors = m_SavedProperties.FindPropertyRelative("m_Colors");

                Delete(m_TexEnvs);
                Delete(m_Floats);
                Delete(m_Colors);
                so.ApplyModifiedProperties();
             
                void Delete(SerializedProperty property)
                {
                    for (int i = property.arraySize - 1; i >= 0; i--)
                    {
                        var prop = property.GetArrayElementAtIndex(i);
                        string propertyName = prop.displayName;
                        if (!mat.HasProperty(propertyName))
                        {
                            property.DeleteArrayElementAtIndex(i);
                        }
                    }
                }
            });

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

    [UnityEditor.MenuItem("AssetTools/Mip")]
    public static void Mip()
    {
        AssetDatabase.FindAssets("t:texture2D", new string[] { "Assets" })
            .Select(guid => AssetDatabase.GUIDToAssetPath(guid))
            .Where(path =>
            { 
                var imp = AssetImporter.GetAtPath(path) as TextureImporter;
                return imp.mipmapEnabled == true;
            })
            .ForEach(path =>
            {
                Debug.LogError(path, AssetDatabase.LoadAssetAtPath<Texture2D>(path));
            });
    }

    public static bool GetFlag(int num)
    {
        if (num < 1) return false;
        return (num & num - 1) == 0;
    }

    const string AndroidPlatform = "Android";
    const string IPhonePlatform = "iPhone";

    不合理图片
    //[UnityEditor.MenuItem("AssetTools/检测图片大小问题")]
    //public static void BH()
    //{
    //    int particle = 512;

    //    var paths = AssetDatabase.FindAssets("t:texture2D", new string[] {
    //        "Assets"
    //    }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

    //    var imps = paths.Select(path => AssetImporter.GetAtPath(path) as TextureImporter).Where(imp => imp != null);
    //    imps.Where(imp =>
    //    {
    //        var t2d = AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath);
    //        if (t2d == null)
    //            return false;
    //        return t2d.width > particle && t2d.height > particle && (t2d.width % 4 != 0 || t2d.height % 4 != 0);
    //    }).ForEach(imp =>
    //    {
    //        Debug.LogError(imp.assetPath, AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath));
    //    });
    //}

    //检测并导出超大图片
    [UnityEditor.MenuItem("AssetTools/检测并导出超大图片")]
    public static void CheckOversizeTextures()
    {
        int particle = 512;

        var paths = AssetDatabase.FindAssets("t:texture2D", new string[] {
            "Assets"
        }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

        List<string> lines = new List<string>();
        var imps = paths.Select(path => AssetImporter.GetAtPath(path) as TextureImporter).Where(imp => imp != null);
        imps.Where(imp =>
        {
            var t2d = AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath);
            if (t2d == null)
                return false;
            var no4 = particle >= 2048 ? true : (t2d.width % 4 != 0 || t2d.height % 4 != 0);
            var oversize = t2d.width > particle || t2d.height > particle;
            return oversize && no4;
        }).ForEach(imp =>
        {
            lines.Add(imp.assetPath);
            Debug.LogError(imp.assetPath, AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath));
        });

        CopyFile($"D:/Work/MNJT_Res/Res_{particle}/", lines);
        //SaveTxtFile(lines, $"OversizeTexture{particle}.txt", $"超过{particle}的图片导出路径:", $"未找到大小超过{particle}的图片");
    }

    //检测并导出可能可以九宫的图片
    [UnityEditor.MenuItem("AssetTools/检测并导出可能可以九宫的图片")]
    public static void Check9CellTextures()
    {
        int particle = 512;
        float prefRate = 1 / 2f;

        var paths = AssetDatabase.FindAssets("t:texture2D", new string[] {
            "Assets"
        }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

        List<string> lines = new List<string>();
        var imps = paths.Select(path => AssetImporter.GetAtPath(path) as TextureImporter).Where(imp => imp != null);
        imps.Where(imp =>
        {
            var t2d = AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath);
            if (t2d == null)
                return false;

            var maxSide = t2d.width > t2d.height ? t2d.width : t2d.height;
            var minSide = t2d.width < t2d.height ? t2d.width : t2d.height;
            var baseSize = maxSide > 0 ? maxSide : 1;
            var rate = minSide * 1f / baseSize;

            var oversize = t2d.width > particle || t2d.height > particle;
            return oversize && rate <= prefRate;
        }).ForEach(imp =>
        {
            lines.Add(imp.assetPath);
            Debug.LogError(imp.assetPath, AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath));
        });

        CopyFile($"D:/Work/MNJT_Res/Res_{particle}_9/", lines);
        //SaveTxtFile(lines, $"OversizeTexture9Cell{particle}.txt", "可能可以九宫的图片导出路径:", "未找到符合条件的图片!!");
    }

    //检测并导出所有文件名有空格的文件
    [UnityEditor.MenuItem("AssetTools/检测并导出文件名有空格的文件")]
    public static void CheckIllegalFileName()
    {
        List<string> lines = new List<string>();
        List<string> filters = new List<string>() {"t:texture2D", "t:Shader", "t:Material",
            "t:Mesh", "t:AudioClip", "t:VideoClip", "t:prefab", "t:Scene" };
        foreach (var item in filters)
        {
            var l = FindIllegalFileName(item);
            if (null != l && l.Count > 0) lines.AddRange(l);
        }

        //写文件
        SaveTxtFile(lines, "FileNameContainSpace.txt", "文件名包含空格的文件导出路径:", "未找到符合条件的文件!!");
    }

    private static List<string> FindIllegalFileName(string filter)
    {
        var paths = AssetDatabase.FindAssets(filter, new string[] {
            "Assets"
        }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

        List<string> lines = null;
        paths.Where(path => !string.IsNullOrEmpty(path) && path.Contains(" ")).ForEach(_path =>
        {
            if (null == lines) lines = new List<string>();
            lines.Add(_path);
            Debug.LogError(_path);
        });
        return lines;
    }

    private static void SaveTxtFile(List<string> txt, string fileName, string sucLog, string errLog)
    {
        if (txt.Count < 1)
        {
            Debug.LogError(errLog);
            return;
        }
        string foldPath = $"{Application.dataPath}/TextureError";
        string fullPath = $"{foldPath}/{fileName}";
        if (!Directory.Exists(foldPath))
        {
            Directory.CreateDirectory(foldPath);
        }
        if (File.Exists(fullPath))
        {
            File.Delete(fullPath);
        }
        File.WriteAllLines(fullPath, txt);
        Debug.LogError($"{sucLog}{fullPath}");
    }

    private static void CopyFile(string rootPath, List<string> paths)
    {
        if (Directory.Exists(rootPath))
        {
            Directory.Delete(rootPath, true);
        }
        for (int i = 0; i < paths.Count; i++)
        {
            string path = paths[i].Replace(Application.dataPath, rootPath).Replace("Assets", "");
            if (!Directory.Exists(new FileInfo(rootPath + path).Directory.FullName))
            {
                Directory.CreateDirectory(new FileInfo(rootPath + path).Directory.FullName);
            }
            if (File.Exists(rootPath + path))
            {
                File.Delete(rootPath + path);
            }
            File.Copy(Application.dataPath + path, rootPath + path);
        }
    }
    //TxtFileUtil.CopyFile("E:/Work/AA", new List<string>() {"Assets/Atlas/Announcement/gong_tub@3x.png","Assets/Atlas/Babel/img_qizhi_gan5.png"});

    [UnityEditor.MenuItem("AssetTools/检测所有包含特效的预制与场景")]
    public static void CheckAllUsedEffectAssets()
    {
        List<string> filters = new List<string>() { "t:prefab", "t:Scene" };
        foreach (var filter in filters)
        {
            CheckByFilter(filter);
        }

        void CheckByFilter(string filter)
        {
            var isScene = filter.Equals("t:Scene");
            var paths = AssetDatabase.FindAssets(filter, new string[] {
            "Assets"
            }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

            if (isScene)
            {
                var mainScenePath = "";
                paths = paths.Where(path =>
                {
                    var foundPS = false;
                    var scene = EditorSceneManager.OpenScene(path);
                    if (scene.name.Equals("Main")) mainScenePath = path;
                    var objs = scene.GetRootGameObjects();
                    foreach (var obj in objs)
                    {
                        var trans = obj.GetComponentsInChildren<ParticleSystem>(true);
                        if (trans.Length > 0)
                        {
                            foundPS = true;
                            break;
                        }
                    }
                    EditorSceneManager.CloseScene(scene, true);
                    if (foundPS) return true;
                    else return false;
                });
                paths.ForEach(path =>
                {
                    Debug.LogError($"Include ParticleSystem Scene Path : {path}");
                });
                EditorSceneManager.OpenScene(mainScenePath);
            }
            else
            {
                paths = paths.Where(path =>
                {
                    if (!path.Contains("Assets/Art/Prefab/UI/")) return false;
                    var obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                    var trans = obj.GetComponentsInChildren<ParticleSystem>(true);
                    if (trans.Length > 0) return true;
                    else return false;
                });
                paths.ForEach(path =>
                {
                    Debug.LogError($"Include ParticleSystem Prefab Path : {path}", AssetDatabase.LoadAssetAtPath<GameObject>(path));
                });
                Debug.LogError("分割线*****************************************************************************************");
            }
        }
    }

    private const int THRESHOLD_WIDTH = 1024;
    private const int THRESHOLD_HEIGHT = 1024;
    [MenuItem("AssetTools/检测所有包含大图的预制")]
    public static void CheckAllIncludeBigImageAssets()
    {
        CheckByFilter("t:prefab");
        void CheckByFilter(string filter)
        {
            var paths = AssetDatabase.FindAssets(filter, new string[] {
            "Assets"
            }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

            paths = paths.Where(path =>
            {
                if (path.Contains("Eff_") || path.Contains("eff_")) return false;
                var obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                var images = obj.GetComponentsInChildren<UnityEngine.UI.Image>(true);
                var isFound = false;
                foreach (var img in images)
                {
                    var text = img.mainTexture;
                    if (text.width >= THRESHOLD_WIDTH && text.height >= THRESHOLD_HEIGHT)
                    {
                        isFound = true;
                        Debug.LogError($"=========>>Object Name : ->  {img.name}  <- =>> Path : {path}");
                        break;
                    }
                }
                if (isFound) return true;
                else return false;
            });
            paths.ForEach(path =>
            {
                Debug.LogError($"Include Big Image Prefab Path : {path}", AssetDatabase.LoadAssetAtPath<GameObject>(path));
            });
        }
    }

    private static int CheckParticleMaxCount = 50;
    [MenuItem("AssetTools/检测所有特效预制粒子发射数量")]
    public static void CheckAllEffPrefabMaxParticles()
    {
        CheckByFilter("t:prefab");
        void CheckByFilter(string filter)
        {
            var paths = AssetDatabase.FindAssets(filter, new string[] {
            "Assets"
            }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

            List<string> lines = new List<string>();
            paths = paths.Where(path =>
            {
                var obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                var paSys = obj.GetComponentsInChildren<ParticleSystem>(true);
                bool isFound = false;
                var _maxCount = 0f;
                var _maxCount1 = 0f;
                var _limitMaxCount = 0f;
                foreach (var ps in paSys)
                {
                    var _count = ps.emission.rateOverTimeMultiplier;
                    var _limitCount = ps.main.maxParticles;
                    if (_count > _maxCount) _maxCount = _count;
                    var _bMaxCount = 0f;
                    for (int i = 0; i < ps.emission.burstCount; i++)
                    {
                        var brust = ps.emission.GetBurst(i);
                        var bCount = brust.count.curveMultiplier;
                        if (bCount > _bMaxCount) _bMaxCount = bCount;
                    }

                    if (_bMaxCount > _maxCount1) _maxCount1 = _bMaxCount;
                    if (_limitCount < CheckParticleMaxCount || (_count < CheckParticleMaxCount && _bMaxCount < CheckParticleMaxCount)) continue;
                    if (_limitCount > _limitMaxCount) _limitMaxCount = _limitCount;
                    isFound = true;
                }
                if (isFound)
                {
                    var max = _maxCount > _maxCount1 ? _maxCount : _maxCount1;
                    var log = $"Max Particles : {_limitMaxCount} Time Max Count : {max}         Prefab Path : {path}";
                    Debug.LogError(log, AssetDatabase.LoadAssetAtPath<GameObject>(path));
                    lines.Add(log);
                }
                return isFound;
            });
            paths.ForEach(path =>
            {
                //Debug.LogError($"Include Big Image Prefab Path : {path}", AssetDatabase.LoadAssetAtPath<GameObject>(path));
            });

            //写文件
            SaveTxtFile(lines, "MaxParticles.txt", "", "");
        }
    }

    [MenuItem("AssetTools/检测所有Mesh面数")]
    public static void CheckAllMeshTriangleCount()
    {
        CheckByFilter("t:Mesh");
        void CheckByFilter(string filter)
        {
            var paths = AssetDatabase.FindAssets(filter, new string[] {
            "Assets"
            }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));
            List<string> lines = new List<string>();
            paths = paths.Where(path =>
            {
                var _mesh = AssetDatabase.LoadAssetAtPath<Mesh>(path);
                var _count = _mesh.triangles.Length / 3;
                if (_count < 3000) return false;
                var log = $"Mesh Triangles Count : {_count}          Mesh Path : {path}";
                lines.Add(log);
                Debug.LogError(log, AssetDatabase.LoadAssetAtPath<GameObject>(path));
                return true;
            });
            paths.ForEach(path =>
            {
                //Debug.LogError($"Include Big Image Prefab Path : {path}", AssetDatabase.LoadAssetAtPath<GameObject>(path));
            });

            //写文件
            SaveTxtFile(lines, "MeshMaxTriangles.txt", "", "");
        }
    }

    [MenuItem("AssetTools/检测当前场景所有模型面数总和")]
    public static void CheckSceneAllMeshTriangleCount()
    {
        var _scene = EditorSceneManager.GetActiveScene();
        var _objs = _scene.GetRootGameObjects();
        var _totalTriangles = 0;
        foreach (var obj in _objs)
        {
            var trans = obj.GetComponentsInChildren<Transform>(true);
            foreach (Transform tran in trans)
            {
                Mesh _mesh = null;
                var _mf = tran.GetComponent<MeshFilter>();
                if (null != _mf) _mesh = _mf.sharedMesh;
                else
                {
                    var _sm = tran.GetComponent<SkinnedMeshRenderer>();
                    if (null != _sm) _mesh = _sm.sharedMesh;
                }
                if (null == _mesh) continue;
                _totalTriangles += _mesh.triangles.Length / 3;
            }
        }
        Debug.LogError($"Current Scene Total Mesh Triangles : {_totalTriangles}     Scene Path : {_scene.path}");
    }

    //[MenuItem("AssetTools/检测所有特效order ID")]
    //public static void CheckAllEff()
    //{
    //    CheckByFilter("t:prefab");
    //    void CheckByFilter(string filter)
    //    {
    //        var paths = AssetDatabase.FindAssets(filter, new string[] {
    //        "Assets"
    //        }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

    //        paths = paths.Where(path =>
    //        {
    //            var obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
    //            var paSys = obj.GetComponentsInChildren<ParticleSystem>(true);
    //            var isFound = false;
    //            foreach (var ps in paSys)
    //            {
    //                var _render = ps.GetComponent<Renderer>();
    //                if (null == _render) continue;
    //                if (_render.sortingOrder > 102 && _render.sortingOrder < 105)
    //                {
    //                    isFound = true;
    //                }
    //            }
    //            if(isFound) Debug.LogError($"Effect Order Id : 103-104          Path : {path}", AssetDatabase.LoadAssetAtPath<GameObject>(path));
    //            return isFound;
    //        });
    //        paths.ForEach(path =>
    //        {
    //            //Debug.LogError($"Include Big Image Prefab Path : {path}", AssetDatabase.LoadAssetAtPath<GameObject>(path));
    //        });
    //    }
    //}

    [MenuItem("AssetTools/检测所有冗余的ParticleSystem")]
    public static void CheckAllUnusedParticleSystem()
    {
        CheckByFilter("t:prefab");
        void CheckByFilter(string filter)
        {
            var paths = AssetDatabase.FindAssets(filter, new string[] {
            "Assets"
            }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

            paths = paths.Where(path =>
            {
                var obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                var paSys = obj.GetComponentsInChildren<ParticleSystem>(true);
                List<string> _unusedPsName = new List<string>();
                bool isFound = false;
                foreach (var ps in paSys)
                {
                    var r = ps.GetComponent<Renderer>();
                    if (ps.emission.enabled && r.enabled) continue;
                    _unusedPsName.Add(ps.name);
                    isFound = true;
                }
                if (isFound)
                {
                    var log = $"Unused PS Prefab Path : {path}";
                    Debug.LogError(log, AssetDatabase.LoadAssetAtPath<GameObject>(path));
                    foreach (var psName in _unusedPsName)
                    {
                        Debug.LogError($"{obj.name}中无效的粒子特效:{psName}");
                    }
                }
                return isFound;
            });
            paths.ForEach(path =>
            {
                //Debug.LogError($"Include Big Image Prefab Path : {path}", AssetDatabase.LoadAssetAtPath<GameObject>(path));
            });
        }
    }

    [UnityEditor.MenuItem("AssetTools/导出所有预制中的中文")]
    public static void ExportAllTextString()
    {
        List<string> filters = new List<string>() { "t:prefab", "t:Scene" };
        List<string> lines = new List<string>();
        foreach (var filter in filters)
        {
            CheckByFilter(filter, lines);
        }
        Debug.LogError("结束*****************************************************************************************");
        //写文件
        SaveTxtFile(lines, "AllPrefabText.txt", "", "");

        void CheckByFilter(string filter, List<string> _lines)
        {
            var isScene = filter.Equals("t:Scene");
            var paths = AssetDatabase.FindAssets(filter, new string[] {
            "Assets"
            }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

            if (isScene)
            {
                var mainScenePath = "";
                paths = paths.Where(path =>
                {
                    var foundPS = false;
                    var scene = EditorSceneManager.OpenScene(path);
                    if (scene.name.Equals("Main")) mainScenePath = path;
                    var objs = scene.GetRootGameObjects();
                    foreach (var obj in objs)
                    {
                        var _txts = obj.GetComponentsInChildren<UnityEngine.UI.Text>(true);
                        if (_txts.Length < 1) continue;
                        foreach (var txt in _txts)
                        {
                            var _tt = txt.text;
                            if (string.IsNullOrEmpty(_tt)) continue;
                            if (!IncludeChineseChar(_tt)) continue;
                            _lines.Add(_tt);
                            foundPS = true;
                        }
                    }
                    EditorSceneManager.CloseScene(scene, true);
                    if (foundPS) return true;
                    else return false;
                });
                paths.ForEach(path =>
                {
                    //Debug.LogError($"Include ParticleSystem Scene Path : {path}");
                });
                EditorSceneManager.OpenScene(mainScenePath);
            }
            else
            {
                paths = paths.Where(path =>
                {
                    if (!path.Contains("Assets/Art/Prefab/UI/")) return false;
                    var obj = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                    var _txts = obj.GetComponentsInChildren<UnityEngine.UI.Text>(true);
                    if (_txts.Length > 0)
                    {
                        foreach (var txt in _txts)
                        {
                            var _tt = txt.text;
                            if (string.IsNullOrEmpty(_tt)) continue;
                            if (!IncludeChineseChar(_tt)) continue;
                            _lines.Add(_tt);
                        }
                        return true;
                    }
                    else return false;
                });
                paths.ForEach(path =>
                {
                    //Debug.LogError($"Include ParticleSystem Prefab Path : {path}", AssetDatabase.LoadAssetAtPath<GameObject>(path));
                });
                //Debug.LogError("分割线*****************************************************************************************");
            }
        }
    }

    /// <summary>
    /// 是否包含中文字符
    /// </summary>
    /// <param name="str">被检测字符串</param>
    /// <returns>是否</returns>
    private static bool IncludeChineseChar(string str)
    {
        bool bRet = false;
        if (!string.IsNullOrEmpty(str))
        {
            var chars = str.ToCharArray();
            foreach (var ch in chars)
            {
                if (ch >= 0x4e00 && ch <= 0x9fbb)
                {
                    bRet = true;
                    break;
                }
            }
        }
        return bRet;
    }

    

    //检测开启透明通道的贴图
    [UnityEditor.MenuItem("AssetTools/检测开启透明通道的贴图")]
    public static void CheckUsedAlphaTextures()
    {
        List<string> lines = new List<string>();
        var paths = AssetDatabase.FindAssets("t:texture", new string[] {
            "Assets"
        }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

        var imps = paths.Select(path => AssetImporter.GetAtPath(path) as TextureImporter).Where(imp => imp != null);
        imps.Where(imp =>
        {
            var t2d = AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath);
            if (t2d == null)
                return false;
            return imp.alphaSource == TextureImporterAlphaSource.FromInput && !imp.DoesSourceTextureHaveAlpha();
        }).ForEach(imp =>
        {
            lines.Add(imp.assetPath);
            Debug.LogError(imp.assetPath, AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath));
        });

        //写文件
        SaveTxtFile(lines, "UsedAlphaTextures.txt", "开启透明设置的图片有:", "未找到符合条件的图片!!");
    }

    /// <summary>
    /// 图片规则
    /// 1.无透明通道并且满足2的幂次 ETC_RGB4Crunched 
    /// 2.无透明通道并且宽高都是4的倍数  ETC2_RGBA8Crunched
    /// 3.有透明通道 ETC2_RGBA8Crunched
    /// 4.除碎小ui图片外都必须满足宽高均为4的倍数
    /// </summary>
    [UnityEditor.MenuItem("AssetTools/安卓平台图片推荐设置")]
    public static void YS()
    {
        var paths = AssetDatabase.FindAssets("t:texture2D", new string[] {
            "Assets"
        }).Select(guid => AssetDatabase.GUIDToAssetPath(guid));

        var imps = paths.Select(path => AssetImporter.GetAtPath(path) as TextureImporter).Where(imp => imp != null);

        imps
            .Where(imp => !imp.assetPath.EndsWith("exr"))
            .Where(imp => imp.alphaSource == TextureImporterAlphaSource.None || imp.assetPath.EndsWith("jpg") || imp.assetPath.EndsWith("JPG"))
            .Where(imp =>
            {
                var t2d = AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath);
                return GetFlag(t2d.width) && GetFlag(t2d.height);
            }).ForEach(imp =>
            {
                var set = imp.GetPlatformTextureSettings(AndroidPlatform);
                if (set.format != TextureImporterFormat.ETC_RGB4Crunched)
                {
                    Debug.LogError(imp.assetPath, AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath));
                }
            });


        imps
            .Where(imp => (imp.assetPath.EndsWith("png") || imp.assetPath.EndsWith("Png")) && imp.alphaSource != TextureImporterAlphaSource.None)
            .ForEach(imp =>
            {
                var set = imp.GetPlatformTextureSettings(AndroidPlatform);
                if (set.format != TextureImporterFormat.ETC2_RGBA8Crunched)
                {
                    Debug.LogError(imp.assetPath, AssetDatabase.LoadAssetAtPath<Texture2D>(imp.assetPath));
                }
            });
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值