DarkRewar/BaseTool

Add ValueListener<T>

Closed this issue · 0 comments

I've made this script to avoid using Value/OnChangedValue pattern in many scripts. Like, if I have a Player, and I want to subscribe to any of its fields, it would make many many lines. So I packed this into:

public class ValueListener<T>
{
    private T _value;
    public T Value
    {
        get => _value;
        set
        {
            var oldValue = _value;
            _value = value;
            OnChanged?.Invoke(oldValue, _value);
        }
    }

    public event Action<T, T> OnChanged;

    public ValueListener() => _value = default;

    public ValueListener(T value) => _value = value;

    public static implicit operator ValueListener<T>(T value) => new(value);
    public static implicit operator T(ValueListener<T> listener) => listener.Value;
}

It could be used like:

public readonly ValueListener<string> Name = "DefaultName";
public Text Label;

public void OnEnable()
{
    Name.OnChanged += (_, newValue) => Label.text = newValue;
}

public void Start()
{
    string name = Name;
    if(name == "DefaultName") Name.Value = "MyNewName";
}