「Unity/MVP」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→手順) |
|||
| 行54: | 行54: | ||
{ | { | ||
[SerializeField] private CounterView _counterView; | [SerializeField] private CounterView _counterView; | ||
| + | private CounterModel _counterModel; | ||
void Start() | void Start() | ||
{ | { | ||
| − | + | _counterModel = new CounterModel(); | |
| − | _counterView.SetValueText( | + | _counterView.SetValueText(_counterModel.Counter); |
_counterView.plusButton | _counterView.plusButton | ||
.OnClickAsObservable() | .OnClickAsObservable() | ||
.Subscribe(_ => { | .Subscribe(_ => { | ||
| − | + | _counterModel.PlusCounter(); | |
| − | _counterView.SetValueText( | + | _counterView.SetValueText(_counterModel.Counter); |
}) | }) | ||
.AddTo(this); | .AddTo(this); | ||
| 行71: | 行72: | ||
.OnClickAsObservable() | .OnClickAsObservable() | ||
.Subscribe(_ => { | .Subscribe(_ => { | ||
| − | + | _counterModel.MinusCounter(); | |
| − | _counterView.SetValueText( | + | _counterView.SetValueText(_counterModel.Counter); |
}) | }) | ||
.AddTo(this); | .AddTo(this); | ||
| + | } | ||
| + | void OnDestroy() | ||
| + | { | ||
| + | Destroy(this); | ||
} | } | ||
} | } | ||
2021年9月15日 (水) 03:59時点における版
MVPとは
MV(R)Pで、ModelとViewとPresenterをReactiveで、疎結合に連携したパターン
準備
- UniRxをインストールしておく。
Unity/UniRx [ショートカット]
サンプル
CounterModel.cs
public class CounterModel
{
public int Counter {
get => counter;
set => counter = value;
}
int counter = 0;
public void PlusCounter()
{
counter++;
}
public void MinusCounter()
{
counter--;
}
}
CounterView.cs
using UnityEngine;
using UnityEngine.UI;
public class CounterView : MonoBehaviour
{
[SerializeField] public Button minusButton, plusButton;
[SerializeField] public Text text;
public void SetValueText(float value)
{
text.text = value.ToString();
}
}
CounterPresenter.cs
using UnityEngine;
using UniRx;
public class CounterPresenter : MonoBehaviour
{
[SerializeField] private CounterView _counterView;
private CounterModel _counterModel;
void Start()
{
_counterModel = new CounterModel();
_counterView.SetValueText(_counterModel.Counter);
_counterView.plusButton
.OnClickAsObservable()
.Subscribe(_ => {
_counterModel.PlusCounter();
_counterView.SetValueText(_counterModel.Counter);
})
.AddTo(this);
_counterView.minusButton
.OnClickAsObservable()
.Subscribe(_ => {
_counterModel.MinusCounter();
_counterView.SetValueText(_counterModel.Counter);
})
.AddTo(this);
}
void OnDestroy()
{
Destroy(this);
}
}
手順
- SampleSceneのヒエラルキーにTextとPlusButtonとMinusButtonを作成する。
- ヒエラルキーにGameObjectを作成して、CounterViewと変更する。CounterView.csをAddComponentする。
- CounterPresenter.csをMainCanvasにAddComponentする。
- CounterViewオブジェクトを選択し、インスペクターのCounterViewの部分にそれぞれのUIをドラッグする。
- MainCanvasのCounterPresenterにCounterViewオブジェクトをドラッグする。
