Last active
July 27, 2022 17:05
-
-
Save arcueid-dev/9598ed2b65382539491997032b659409 to your computer and use it in GitHub Desktop.
Unity EventValue. Use this to avoid additional actions. Just set value to "Value" property and if it's different from stored, then action is invoked.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [Serializable] | |
| public class EventValue<T> | |
| { | |
| [SerializeField] private T _value; | |
| private Action<T> _action; | |
| public event Action<T> OnValueChanged | |
| { | |
| add | |
| { | |
| _action += value; | |
| value?.Invoke(_value); | |
| } | |
| remove => _action -= value; | |
| } | |
| public T Value | |
| { | |
| get => _value; | |
| set | |
| { | |
| if (!EqualityComparer<T>.Default.Equals(_value, value)) | |
| { | |
| _action?.Invoke(value); | |
| } | |
| _value = value; | |
| } | |
| } | |
| public EventValue(T value, Action<T> action) | |
| { | |
| _value = value; | |
| _action = action; | |
| _action?.Invoke(_value); | |
| } | |
| public EventValue(T value, Action<T> action, bool invokeOnInitialize) | |
| { | |
| _value = value; | |
| _action = action; | |
| if (invokeOnInitialize) _action?.Invoke(_value); | |
| } | |
| public EventValue(T value) | |
| { | |
| _value = value; | |
| _action = null; | |
| } | |
| public EventValue(Action<T> action, bool invokeOnInitialize = false) | |
| { | |
| _value = default; | |
| _action = action; | |
| if (invokeOnInitialize) _action?.Invoke(_value); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment