facebook twitter hatena line email

Unity/MVP/値変更を自動でViewへ適用

提供: 初心者エンジニアの簡易メモ
2021年9月15日 (水) 16:41時点におけるAdmin (トーク | 投稿記録)による版

移動: 案内検索

サンプル

CounterModel.cs

using UnityEngine;
using UniRx;

public class CounterModel : MonoBehaviour
{
    public int Counter {
        get => counterRP.Value;
        set => counterRP.Value = value;
    }
    public IntReactiveProperty counterRP = new IntReactiveProperty();

    public void PlusCounter()
    {
        counterRP.Value++;
    }
    public void MinusCounter()
    {
        counterRP.Value--;
    }
    public void SetCounter(int value)
    {
        counterRP.Value = value;
    }
}

CounterView.cs

using UnityEngine;
using UnityEngine.UI;

public class CounterView : MonoBehaviour
{
    [SerializeField] public Button minusButton, plusButton, refreshButton;
    [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;
    [SerializeField] private CounterModel _counterModel;

    void Start()
    {
        _counterView.SetValueText(_counterModel.Counter);

        _counterView.plusButton
            .OnClickAsObservable()
            .Subscribe(_ => {
                _counterModel.PlusCounter();
            })
            .AddTo(this);

        _counterView.minusButton
            .OnClickAsObservable()
            .Subscribe(_ => {
                _counterModel.MinusCounter();
            })
            .AddTo(this);

        _counterView.refreshButton
            .OnClickAsObservable()
            .Subscribe(_ => {
                _counterModel.SetCounter(_counterModel.Counter);
            })
            .AddTo(this);
        // 値が変更したらView更新イベント発生
        _counterModel.counterRP.Subscribe(value => {
            _counterView.SetValueText(_counterModel.Counter);
        });
    }
    void OnDestroy()
    {
        Destroy(this);
    }
}

手順

  1. SampleSceneのヒエラルキーにTextとPlusButtonとMinusButtonとRefreshButtonを作成する。
  2. ヒエラルキーにGameObjectを作成して、CounterViewに名前を変更する。CounterView.csをAddComponentする。
  3. ヒエラルキーにGameObjectを作成して、CounterModelに名前を変更する。CounterModel.csをAddComponentする。
  4. CounterPresenter.csをMainCanvasにAddComponentする。
  5. CounterViewオブジェクトを選択し、インスペクターのCounterViewの部分にそれぞれのUIをドラッグする。
  6. MainCanvasのCounterPresenterにCounterViewオブジェクトとCounterModelオブジェクトをドラッグする。

参考

https://qiita.com/Nakashima_Toshiki/items/5e0c36c3b0df78110d32