| | 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 | | { |
| | 15 | | DrawDefaultInspector(); |
| | 16 | | if (Application.isPlaying && GUILayout.Button("Raise OnChange")) |
| | 17 | | { |
| | 18 | | ((BaseVariableAsset)target).RaiseOnChange(); |
| | 19 | | } |
| | 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 delegate void Same(T current); |
| | 30 | |
|
| | 31 | | public event Same OnSame; |
| | 32 | | public event Change OnChange; |
| | 33 | |
|
| | 34 | | [SerializeField] protected T value; |
| | 35 | |
|
| | 36 | | public void Set(T newValue) |
| | 37 | | { |
| 40131 | 38 | | if (Equals(newValue)) |
| | 39 | | { |
| 22561 | 40 | | OnSame?.Invoke(newValue); |
| 0 | 41 | | return; |
| | 42 | | } |
| | 43 | |
|
| 17570 | 44 | | var previous = value; |
| 17570 | 45 | | value = newValue; |
| 17570 | 46 | | OnChange?.Invoke(value, previous); |
| 551 | 47 | | } |
| | 48 | |
|
| 232451 | 49 | | public T Get() { return value; } |
| | 50 | |
|
| 45858 | 51 | | public static implicit operator T(BaseVariableAsset<T> value) => value.value; |
| | 52 | |
|
| | 53 | | public virtual bool Equals(T other) |
| | 54 | | { |
| | 55 | | //NOTE(Brian): According to benchmarks I made, this statement costs about twice than == operator for structs. |
| | 56 | | // However, its way more costly for primitives (tested only against float). |
| | 57 | |
|
| | 58 | | // Left here only for fallback purposes. Optimally this method should be always overriden. |
| 60 | 59 | | return EqualityComparer<T>.Default.Equals(value, other); |
| | 60 | | } |
| | 61 | |
|
| | 62 | | #if UNITY_EDITOR |
| 0 | 63 | | protected sealed override void RaiseOnChange() => OnChange?.Invoke(value, value); |
| | 64 | |
|
| | 65 | | private void OnEnable() |
| | 66 | | { |
| 6847 | 67 | | Application.quitting -= CleanUp; |
| 6847 | 68 | | Application.quitting += CleanUp; |
| 6847 | 69 | | } |
| | 70 | |
|
| | 71 | | private void CleanUp() |
| | 72 | | { |
| 0 | 73 | | Application.quitting -= CleanUp; |
| 0 | 74 | | if (UnityEditor.AssetDatabase.Contains(this)) //It could happen that the base variable has been created in runti |
| 0 | 75 | | Resources.UnloadAsset(this); |
| 0 | 76 | | } |
| | 77 | | #endif |
| | 78 | | } |