/****************************************************************************
* Copyright (c) 2016 ~ 2024 liangxiegame UNDER MIT LICENSE
*
* https://qframework.cn
* https://github.com/liangxiegame/QFramework
* https://gitee.com/liangxiegame/QFramework
****************************************************************************/
using System;
using UnityEngine.Events;
namespace QFramework
{
///
///
///
///
[Serializable]
public class Property
{
///
///
///
public Property()
{
}
///
///
///
protected bool mSetted = false;
///
///
///
///
public Property(T initValue)
{
mValue = initValue;
}
///
///
///
public T Value
{
get { return GetValue(); }
set { SetValue(value); }
}
///
///
///
///
protected virtual T GetValue()
{
return mValue;
}
///
///
///
///
protected virtual void SetValue(T value)
{
if (IsValueChanged(value))
{
mValue = value;
DispatchValueChangeEvent();
mSetted = true;
}
}
///
///
///
///
///
protected virtual bool IsValueChanged(T value)
{
return value == null || !value.Equals(mValue) || !mSetted;
}
///
///
///
protected virtual void DispatchValueChangeEvent()
{
if (mSetter != null)
{
mSetter.Invoke(mValue);
OnValueChanged.Invoke(mValue);
}
}
///
///
///
protected T mValue;
///
///
///
///
///
public IUnRegister Bind(Action onValueChanged)
{
mSetter += onValueChanged;
return new CustomUnRegister(() => { mSetter -= onValueChanged; });
}
///
///
///
///
///
public IUnRegister BindWithInitialValue(Action onValueChanged)
{
onValueChanged.Invoke(GetValue());
return Bind(onValueChanged);
}
///
///
///
public void UnBindAll()
{
mSetter = null;
}
private event Action mSetter = t => { };
public UnityEvent OnValueChanged = new OnPropertyChangedEvent();
}
///
/// Int 类型的 Property
///
[Serializable]
public class IntProperty : Property
{
///
/// 值
///
public new int Value
{
get { return base.Value; }
set { base.Value = value; }
}
}
public class OnPropertyChangedEvent : UnityEvent
{
}
///
///
///
///
public class CustomProperty : Property
{
private Func mValueGetter = null;
private Action mValueSetter = null;
///
///
///
///
///
public CustomProperty(Func valueGetter, Action valueSetter = null)
{
mValueGetter = valueGetter;
mValueSetter = valueSetter;
}
///
///
///
///
protected override T GetValue()
{
mValue = mValueGetter.Invoke();
return mValue;
}
///
///
///
///
protected override void SetValue(T value)
{
if (IsValueChanged(value))
{
mValue = value;
DispatchValueChangeEvent();
mSetted = true;
if (mValueSetter != null) mValueSetter(value);
}
}
}
}