有没有可能让RactiveProperty在UniRx中公开并私有化



我有两个类。其中一个具有BoolReactiveProperty。我希望第二个类只能订阅,而不能更改值。这是我当前的代码

public class SourceToggle : MonoBehaviour
{
public BoolReactiveProperty boolRP { get; private set; } 
= new BoolReactiveProperty();
private void Start()
{
boolRP.Subscribe(b => GetComponent<Toggle>().isOn = b);
GetComponent<Toggle>()
.OnValueChangedAsObservable()
.Subscribe(b => boolRP.SetValueAndForceNotify(b));
}
}
public class SubscribedToggle : MonoBehaviour
{
[SerializeField]
private SourceToggle sourceToggle;
private void Start()
{
sourceToggle.boolRP
.Subscribe(b => GetComponent<Toggle>().isOn = b);
GetComponent<Toggle>()
.OnValueChangedAsObservable()
.Subscribe(b => sourceToggle.boolRP.SetValueAndForceNotify(b));
}
}

我没有完全得到你想要阻止的。我想你想阻止你的SubscribedToggle在你的ReactiveProperty上调用SetValueAndForceNotify

然后在SourceToggle类中声明一个公共IReadOnlyReactiveProperty并管理一个私有BoolReactiveProperty

public class SourceToggle : MonoBehaviour
{
private BoolReactiveProperty isOn;
private Toggle toggle;
public IReadOnlyReactiveProperty<bool> IsOn => isOn;
private void Awake()
{
toggle = GetComponent<Toggle>();
isOn = new BoolReactiveProperty(toggle.isOn);
toggle
.OnValueChangedAsObservable()
.Subscribe(b => isOn.SetValueAndForceNotify(b));
isOn.Subscribe(b => toggle.isOn = b);
}
}
public class SubscribedToggle : MonoBehaviour
{
[SerializeField]
private SourceToggle sourceToggle;
private void Start()
{
sourceToggle.IsOn
.Subscribe(b => GetComponent<Toggle>().isOn = b);
// GetComponent<Toggle>()
//     .OnValueChangedAsObservable()
//     .Subscribe(b => sourceToggle.IsOn.SetValueAndForceNotify(b)); // Impossible to call SetValueAndForceNotify
}
}

感谢@Hellium,我找到了解决方案

public class SourceToggle : MonoBehaviour
{
public ReadOnlyReactiveProperty<bool> IsOn { get; private set; }
private void Awake()
{
Toggle toggle = GetComponent<Toggle>();
IsOn = new ReadOnlyReactiveProperty<bool>(toggle.OnValueChangedAsObservable());
}
}
public class SubscribedToggle : MonoBehaviour
{
[SerializeField]
private SourceToggle sourceToggle;
private void Start()
{
Toggle toggle = GetComponent<Toggle>();
sourceToggle.IsOn
.Subscribe(b => toggle.isOn = b);
}
}

相关内容

  • 没有找到相关文章

最新更新