-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVariableBaseSO.cs
More file actions
70 lines (56 loc) · 2.36 KB
/
VariableBaseSO.cs
File metadata and controls
70 lines (56 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using UnityEngine;
using UnityEngine.Events;
using Xprees.Core;
using Xprees.Variables.Utils;
namespace Xprees.Variables.Base
{
public abstract class VariableBaseSO : DescriptionBaseSO
{
private void OnEnable()
{
hideFlags = HideFlags.DontUnloadUnusedAsset;
ForceResetState();
}
/// Force reset state regardless of any protection settings.
public abstract void ForceResetState();
public override void ResetState() => ForceResetState();
}
/// <summary>
/// Base class for all variables ScriptableObjects.
/// Object holds the state on runtime, but reset every time OnEnable to defaultValue.
/// </summary>
/// <typeparam name="T">Unity Serializable or System.Serializable</typeparam>
public class VariableBaseSO<T> : VariableBaseSO
{
[Tooltip("Value to which the variable will be reset on OnEnable or ResetState call.")]
[SerializeField] protected T defaultValue;
[Tooltip("Current value of variable - Runtime only value.")]
[SerializeField] private T currentValue;
[Header("Settings")]
[Tooltip("If true, the variable will not be reset when calling ResetState()."
+ " However, it will still be reset on OnEnable and when ForceResetState() is called. "
+ "Useful for game-system variables where runtime value should persist unless explicitly reset.")]
[SerializeField] protected bool protectedDontReset = false;
public virtual T CurrentValue
{
get => currentValue;
set
{
currentValue = value;
onValueChanged?.Invoke(value);
}
}
/// Event invoked when CurrentValue changes.
public UnityAction<T> onValueChanged;
public void SetValue(T value) => CurrentValue = value;
public void SetValue(VariableBaseSO<T> variable) => CurrentValue = variable.CurrentValue;
public static implicit operator T(VariableBaseSO<T> variable) =>
variable != null ? variable.CurrentValue : default;
public override void ResetState()
{
if (protectedDontReset) return; // skip reset if protected
ForceResetState();
}
public override void ForceResetState() => CurrentValue = CloningTools.Clone(defaultValue);
}
}