38. 値+イベントの表現
[Serializable]
public class Character : MonoBehaviour
{
public Action<int> HpChanged;
[SerializeField]
int hp = 0;
public int Hp
{
get
{
return hp;
}
set
{
hp = value;
var h = HpChanged;
if (h != null)
{
h.Invoke(hp);
}
}
[Serializable]
public class Character : MonoBehaviour
{
public IntReactiveProperty Hp;
}
40. Unity + Rxに適したUIパターン
Passive View
Presenter
(Supervising Controller)
Model
updates view
state-change
events
user events
update model
UIControl.XxxAsObservable
UnityEvent.AsObservable
ObservableEventTrigger
Subscribe
ToReactiveProperty
ReactiveProperty
Subscribe
SubscribeToText
SubscribeToInteractable
41. public class CalculatorPresenter : MonoBehaviour
{
public InputField Left;
public InputField Right;
public Text Result;
void Start()
{
var left = this.Left
.OnValueChangeAsObservable()
.Select(x => int.Parse(x));
var right = this.Right
.OnValueChangeAsObservable()
.Select(x => int.Parse(x));
left.CombineLatest(right, (l, r) => l + r)
.SubscribeToText(this.Result);
}
}
42. インスペクタで貼り付けるPの抱える問題
// 子供。これはまぁ普通
[Serializable]
public class ChildPresenter : MonoBehaviour
{
public IntReactiveProperty Hp; // serializable
public ReadOnlyReactiveProperty<bool> IsDead
{ get; private set; }
void Start()
{
IsDead = Hp.Select(x => x <= 0)
.ToReadOnlyReactiveProperty();
}
}
// 親
[Serializable]
public class ParentPresenter : MonoBehaviour
{
public ChildPresenter ChildPresenter;
public Text IsDeadDisplay;
void Start()
{
// IsDeadは触れるか?
ChildPresenter.IsDead
.SubscribeToText(IsDeadDisplay);
}
}
43. インスペクタで貼り付けるPの抱える問題
// 子供。これはまぁ普通
[Serializable]
public class ChildPresenter : MonoBehaviour
{
public IntReactiveProperty Hp; // serializable
public ReadOnlyReactiveProperty<bool> IsDead
{ get; private set; }
void Start()
{
IsDead = Hp.Select(x => x <= 0)
.ToReadOnlyReactiveProperty();
}
}
// 親
[Serializable]
public class ParentPresenter : MonoBehaviour
{
public ChildPresenter ChildPresenter;
public Text IsDeadDisplay;
void Start()
{
// IsDeadは触れるか?
ChildPresenter.IsDead
.SubscribeToText(IsDeadDisplay);
}
}