A game about forced loneliness, made by TACStudios
at master 119 lines 3.5 kB view raw
1using System; 2using System.IO; 3using UnityEditorInternal; 4using UnityEngine; 5using UnityObject = UnityEngine.Object; 6 7namespace UnityEditor.Timeline 8{ 9 class ScriptableObjectViewPrefs<TViewModel> : IDisposable where TViewModel : ScriptableObject 10 { 11 const string k_DefaultFilePath = "Library/"; 12 const string k_Extension = ".pref"; 13 14 readonly string m_RelativePath; 15 readonly string m_AbsolutePath; 16 readonly string m_FileName; 17 ScriptableObject m_Asset; 18 TViewModel m_ViewModel; 19 20 bool isSavable 21 { 22 get 23 { 24 return m_Asset != null && 25 m_ViewModel != null && 26 !string.IsNullOrEmpty(m_FileName); 27 } 28 } 29 30 public ScriptableObjectViewPrefs(ScriptableObject asset, string relativeSavePath) 31 { 32 m_Asset = asset; 33 m_RelativePath = string.IsNullOrEmpty(relativeSavePath) ? k_DefaultFilePath : relativeSavePath; 34 if (!m_RelativePath.EndsWith("/", StringComparison.Ordinal)) 35 m_RelativePath += "/"; 36 37 m_AbsolutePath = Application.dataPath + "/../" + m_RelativePath; 38 39 var assetKey = GetAssetKey(asset); 40 m_FileName = string.IsNullOrEmpty(assetKey) ? string.Empty : assetKey + k_Extension; 41 } 42 43 public TViewModel viewModel 44 { 45 get 46 { 47 if (m_ViewModel == null) 48 { 49 if (m_Asset == null) 50 m_ViewModel = CreateViewModel(); 51 else 52 m_ViewModel = LoadViewModel() ?? CreateViewModel(); 53 } 54 return m_ViewModel; 55 } 56 } 57 58 public void Save() 59 { 60 if (!isSavable) 61 return; 62 63 // make sure the path exists or file write will fail 64 if (!Directory.Exists(m_AbsolutePath)) 65 Directory.CreateDirectory(m_AbsolutePath); 66 67 const bool saveAsText = true; 68 InternalEditorUtility.SaveToSerializedFileAndForget(new UnityObject[] { m_ViewModel }, m_RelativePath + m_FileName, saveAsText); 69 } 70 71 public void DeleteFile() 72 { 73 if (!isSavable) 74 return; 75 76 var path = m_AbsolutePath + m_FileName; 77 78 if (!File.Exists(path)) 79 return; 80 81 File.Delete(path); 82 } 83 84 public void Dispose() 85 { 86 if (m_ViewModel != null) 87 UnityObject.DestroyImmediate(m_ViewModel); 88 89 m_Asset = null; 90 } 91 92 public static TViewModel CreateViewModel() 93 { 94 var model = ScriptableObject.CreateInstance<TViewModel>(); 95 model.hideFlags |= HideFlags.HideAndDontSave; 96 return model; 97 } 98 99 TViewModel LoadViewModel() 100 { 101 if (string.IsNullOrEmpty(m_FileName)) 102 return null; 103 104 var objects = InternalEditorUtility.LoadSerializedFileAndForget(m_RelativePath + m_FileName); 105 if (objects.Length <= 0 || objects[0] == null) 106 return null; 107 108 var model = (TViewModel)objects[0]; 109 model.hideFlags |= HideFlags.HideAndDontSave; 110 111 return model; 112 } 113 114 static string GetAssetKey(UnityObject asset) 115 { 116 return asset == null ? string.Empty : AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(asset)); 117 } 118 } 119}