使ったこと
ReactiveProperty
値(ここでは数値)を持ちつつ,イベントを発行することができる.
ここでは,_contReactivePropertyの値が変わると,
Subscriveで登録されていたイベントが呼ばれる.
Button.OnClickAsObservable
クリックを検知できる.
Where
if文の役割
MV(R)P
ModelとViewとPresenterで構成される.
ここでは,PresenterにそれぞれのView(ボタン)の役割を集中させている.
スクリプト
CountModel.cs
using UnityEngine;
using System.Collections;
using UniRx;
using UnityEngine.UI;
public class CountModel : MonoBehaviour {
// カメラ
[SerializeField]
private Camera _camera;
// カウント表示用テキスト
[SerializeField]
private Text _text;
// カウントの値を持つ & イベントを発行
private ReactiveProperty<int> _countReactiveProperty = new ReactiveProperty<int> (0);
// イベントを購読できるようにする.
public ReactiveProperty<int> CountReactiveProperty{
get{ return _countReactiveProperty; }
}
void Start(){
// カウントをテキストにつっこむイベント
_countReactiveProperty.SubscribeToText(_text);
// 背景色を変えるイベント
_countReactiveProperty
.Where (count => (count / 10) <= 0)
.Subscribe (_=>_camera.backgroundColor = Color.red);
_countReactiveProperty
.Where (count => (count / 10) == 1)
.Subscribe (_=>_camera.backgroundColor = Color.green);
_countReactiveProperty
.Where (count => (count / 10) >= 2)
.Subscribe (_=>_camera.backgroundColor = Color.blue);
}
}
CountPresenter.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UniRx;
public class CountPresenter: MonoBehaviour {
// プラスボタン
[SerializeField]
private Button _plusButton;
// マイナスボタン
[SerializeField]
private Button _minusButton;
void Start () {
var model = this.GetComponent<CountModel> ();
// プラスボタンを押した時のイベント
// カウントに1足す
_plusButton.OnClickAsObservable ().Subscribe (_=>model.CountReactiveProperty.Value += 1);
// マイナスボタンを押した時のイベント
// 0より大きければ,カウントから1引く
_minusButton.OnClickAsObservable ()
.Where(_=> model.CountReactiveProperty.Value > 0)
.Subscribe (_=> model.CountReactiveProperty.Value -= 1);
}
}