[Unity] Find all specific resources under the specified file in the editor

        The requirement is very simple, that is, find all specific resources (UnityEngine.Object) under a certain specified file under the editor. Unity does not provide a dedicated API. At first, I wanted to search for codes on the Internet, but found that there was no ready-made one that could be used directly.

        The function implementation itself is not complicated, and the code is relatively intuitive:

        /// <summary>
        /// 查找在某个文件夹下的所有类型资源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="folder">工程中文件夹相对路径</param>
        /// <param name="result">返回搜索的结果</param>
        public static void FindAssetInFolder<T>(string folder, List<T> result) where T : Object
        {
            if (result == null)
                result = new List<T>();
            result.Clear();

            //定位到指定文件夹
            if (!Directory.Exists(folder))
                return;
            var directory = new DirectoryInfo(folder);

            //查询该文件夹下的所有文件;
            var files = directory.GetFiles();
            int length = files.Length;
            for (int i = 0; i < length; i++)
            {
                var file = files[i];

                //跳过Unity的meta文件(后缀名为.meta)
                if (file.Extension.Contains("meta"))
                    continue;

                //根据路径直接拼出对应的文件的相对路径
                string path = $"{folder}/{file.Name}";
                var asset = AssetDatabase.LoadAssetAtPath<T>(path);
                if (asset != null)
                    result.Add(asset);
            }
        }

        In fact, it borrows the code of System.IO to assist in realizing the query under the editor. The only thing worth noting is that the path to the folder needs to be passed in a relative path.

        The Unity version corresponding to my project is 2020.3.48f1.

Guess you like

Origin blog.csdn.net/cyf649669121/article/details/132294641