using System; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; using UnityEngine.Events; using Object = UnityEngine.Object; public abstract class ResourceScanBase where T : Object { public event UnityAction onFinish; private readonly Predicate _predicate; private string[] _assetPaths; private int _index; protected ResourceScanBase(string extension, string relativeAssetPath = null) { _predicate = a => { if (string.IsNullOrEmpty(relativeAssetPath) || a.StartsWith(relativeAssetPath, StringComparison.OrdinalIgnoreCase)) { var assetExt = Path.GetExtension(a); return string.IsNullOrEmpty(assetExt) ? string.IsNullOrEmpty(extension) : assetExt.Equals(extension, StringComparison.OrdinalIgnoreCase); } else return false; }; } protected ResourceScanBase(Predicate predicate) { _predicate = predicate; } protected void Start() { _assetPaths = (from assetPath in AssetDatabase.GetAllAssetPaths() let extension = Path.GetExtension(assetPath) where _predicate(assetPath) select assetPath).ToArray(); _index = 0; EditorApplication.update += OnEditorUpdate; } private void OnEditorUpdate() { var finish = false; try { if (_index < _assetPaths.Length) { var path = _assetPaths[_index]; var item = AssetDatabase.LoadAssetAtPath(path); if (item != null) FixOneAsset(item, path); _index++; Debug.Log(string.Format("完成扫描{0} / {1}, 路径{2}", _index, _assetPaths.Length, path)); } else { Debug.LogWarning("完成全部扫描"); finish = true; } } catch (Exception e) { Debug.LogError(e.ToString()); Debug.LogError(string.Format("扫描中断于{0}", _index)); finish = true; } if (finish) { EditorApplication.update = null; if(onFinish != null) onFinish.Invoke(); } } protected abstract void FixOneAsset(T asset, string assetPath); }