| | 1 | | using System; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using UnityEngine; |
| | 4 | |
|
| | 5 | | public abstract class BaseVariableAsset : ScriptableObject |
| | 6 | | { |
| | 7 | | #if UNITY_EDITOR |
| | 8 | | protected abstract void RaiseOnChange(); |
| | 9 | |
|
| | 10 | | [UnityEditor.CustomEditor(typeof(BaseVariableAsset), true)] |
| | 11 | | public class BaseVariableAssetEditor : UnityEditor.Editor |
| | 12 | | { |
| | 13 | | public override void OnInspectorGUI() |
| | 14 | | { |
| 0 | 15 | | DrawDefaultInspector(); |
| 0 | 16 | | if (Application.isPlaying && GUILayout.Button("Raise OnChange")) |
| | 17 | | { |
| 0 | 18 | | ((BaseVariableAsset)target).RaiseOnChange(); |
| | 19 | | } |
| 0 | 20 | | } |
| | 21 | | } |
| | 22 | | #endif |
| | 23 | | } |
| | 24 | |
|
| | 25 | | public class BaseVariableAsset<T> : BaseVariableAsset, IEquatable<T> |
| | 26 | | { |
| | 27 | | public delegate void Change(T current, T previous); |
| | 28 | |
|
| | 29 | | public event Change OnChange; |
| | 30 | |
|
| | 31 | | [SerializeField] protected T value; |
| | 32 | |
|
| | 33 | | public void Set(T newValue) |
| | 34 | | { |
| | 35 | | if (Equals(newValue)) |
| | 36 | | return; |
| | 37 | |
|
| | 38 | | var previous = value; |
| | 39 | | value = newValue; |
| | 40 | | OnChange?.Invoke(value, previous); |
| | 41 | | } |
| | 42 | |
|
| | 43 | | public T Get() { return value; } |
| | 44 | |
|
| | 45 | | public static implicit operator T(BaseVariableAsset<T> value) => value.value; |
| | 46 | |
|
| | 47 | | public virtual bool Equals(T other) |
| | 48 | | { |
| | 49 | | //NOTE(Brian): According to benchmarks I made, this statement costs about twice than == operator for structs. |
| | 50 | | // However, its way more costly for primitives (tested only against float). |
| | 51 | |
|
| | 52 | | // Left here only for fallback purposes. Optimally this method should be always overriden. |
| | 53 | | return EqualityComparer<T>.Default.Equals(value, other); |
| | 54 | | } |
| | 55 | |
|
| | 56 | | #if UNITY_EDITOR |
| | 57 | | protected sealed override void RaiseOnChange() => OnChange?.Invoke(value, value); |
| | 58 | |
|
| | 59 | | private void OnEnable() |
| | 60 | | { |
| | 61 | | Application.quitting -= CleanUp; |
| | 62 | | Application.quitting += CleanUp; |
| | 63 | | } |
| | 64 | |
|
| | 65 | | private void CleanUp() |
| | 66 | | { |
| | 67 | | Application.quitting -= CleanUp; |
| | 68 | | if (UnityEditor.AssetDatabase.Contains(this)) //It could happen that the base variable has been created in runti |
| | 69 | | Resources.UnloadAsset(this); |
| | 70 | | } |
| | 71 | | #endif |
| | 72 | | } |