using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace CaoCao.Editor { public class BuildAssetCache : ScriptableObject, ISerializationCallbackReceiver { public List data = new List(); private readonly Dictionary _data = new Dictionary(); public void OnBeforeSerialize() { } public void OnAfterDeserialize() { foreach (var asset in data) _data[asset.path] = asset; } public void BuildReferences() { var references = new Dictionary>(); foreach (var asset in data) { BuildDependenciesIfNeed(asset); foreach (var dependency in asset.dependencies) { if (!references.TryGetValue(dependency, out var value)) { value = new List(); references.Add(dependency, value); } value.Add(asset.path); } } foreach (var asset in data) { if (references.TryGetValue(asset.path, out var value)) { asset.referencesBy = value.ToArray(); } } } public BuildAsset GetAsset(string path) { if (!_data.TryGetValue(path, out var value)) { var type = AssetDatabase.GetMainAssetTypeAtPath(path); value = new BuildAsset { path = path, type = type == null ? "MissType" : type.Name }; _data[path] = value; data.Add(value); EditorUtility.SetDirty(this); } BuildDependenciesIfNeed(value); return value; } private static ulong GetAssetSize(string path) { var file = new FileInfo(path); return (ulong) (file.Exists ? file.Length : 0); } private void BuildDependenciesIfNeed(BuildAsset asset) { var lastWriteTime = Settings.GetLastWriteTime(asset.path); if (asset.lastWriteTime != lastWriteTime) { asset.dependencies = Settings.GetDependenciesWithoutCache(asset.path); asset.lastWriteTime = lastWriteTime; EditorUtility.SetDirty(this); } asset.size = GetAssetSize(asset.path); } public string[] GetDependencies(string path) { return GetAsset(path).dependencies; } } }