DarkRewar / BaseTool

A big library of basic tools that you might need in your Unity projects.
MIT License
45 stars 6 forks source link

Add ValueListener<T> #30

Closed DarkRewar closed 8 months ago

DarkRewar commented 8 months ago

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";
}