unity数据监听BindableProperty

这个来自与凉鞋的qf框架,这里单独将它拿出来写的一篇帖子。

本质上还是利用观察者模式进行的操作,算是一种轻量级的实现方案,属于事件变更的一种。

作用很简单,当数据发生更改时,会引发其它相关的事件发生修改,与消息中心的机制基本一致,但省去消息号的问题,变得更加便捷。

BindableProperty本体:

using System;

public class BindableProperty<T> where T :IEquatable<T>
{
    private T _mValue = default(T);

    public T Value
    {
        get => _mValue;
        set
        {
            if (value.Equals(_mValue)) return;
            _mValue= value;
            OnValueChanged?.Invoke(_mValue);
        }
    }

    public Action<T> OnValueChanged;

}

示例演示代码:

using System;
using UnityEngine;
using UnityEngine.UI;

public class BindExample : MonoBehaviour
{

    public Button Onvalue;
    

    //数据+数据变更事件
    public static BindableProperty<int> _bindable=new BindableProperty<int>()
    {
        Value = 0
    };
    //作为数据存储
    //如果调用此值 BindExample._bindable.value即可调用到此值进行修改
    //如果需要监听数据 BindExample._bindable.OnValueChanged+=OnvalueChange



    // Start is called before the first frame update
    void Start()
    {
        //添加监听事件
        BindExample._bindable.OnValueChanged += OnvalueChange;


        Onvalue.onClick.AddListener(() =>
        {
            //修改参数
            BindExample._bindable.Value++;
        });
    }

    private void OnvalueChange(int numCount)
    {
        //发生变化的事件
        Debug.Log("数据发生了修改改为了"+ numCount);
    }


    void OnDestory()
    {
        //卸载监听
        BindExample._bindable.OnValueChanged -= OnvalueChange;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_46043095/article/details/130814104