LoginSignup
61
49

More than 1 year has passed since last update.

Unityで学ぶMVPパターン ~ UniRxを使って体力Barを作成する ~

Last updated at Posted at 2018-09-22

目次 ― 次の記事

UniRxの基本的な使い方とMVPアーキテクチャパターンについて説明します。

アセットのインポート

以下のアセットを使います。

UniRx - Reactive Extensions for Unity

シーンの作成

大雑把な説明ですが、こんな感じでシーンを作成します。

無題.png

Githubに準備済みのプロジェクトを上げておきます。
00-UniRx-HealthBar-Base

コンポーネントの作成

コンポーネントをModel、View、Presenterで3つ作成して、
MVPパターンでコードを作成します。

コードは体力値を表示する例です。

Model

Modelはビジネスロジックを記述する部分です。
UniRxのIntReactivePropertyでプロパティに変更があった際にイベントを実行できるようにします。

コードのプロパティはプレイヤーの体力値のみです。

StatusModel.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UniRx;

public class StatusModel : MonoBehaviour
{
    public int healthMax = 100;
    public IntReactiveProperty healthRP = new IntReactiveProperty();
    public int Health
    {
        get { return healthRP.Value; }
        set { healthRP.Value = value; }
    }
}

View

MVPのViewはModelもPresenterも知らないので、
これらを宣言しないようにしてください。

コードは体力Barの赤い部分を変更する処理で、これはイベントに登録するメソッドになります。

ParameterBarView.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParameterBarView : MonoBehaviour
{

    public RectTransform valueRect;

    public void SetRate(int max, int value)
    {
        valueRect.localScale = new Vector3((float)value / max, 1, 1);
    }
}

Presenter

PresenterはModelとViewを知っています。
ModelとViewをつなぐ役割をします。

コードはModelのイベントにViewの処理を登録しています。

StatusPresenter.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UniRx;

public class StatusPresenter : MonoBehaviour
{

    public StatusModel model;

    public ParameterBarView healthView;

    void Awake()
    {
        model.healthRP.Subscribe(value => { healthView.SetRate(model.healthMax, value); });
    }
}

コンポーネントの追加

以下の画像のように作成したコンポーネントをゲームオブジェクトに追加します。

あとは、コンポーネントの依存状態をドラッグ&ドロップで設定して完成。

image.png

完成

inspector上で値を変えると体力バーの長さが変わります。

image.png

Githubに完成例を上げておきます。

01-UniRx-HealthBar-Simple

まとめ

大した処理でもないのに、
ファイル数が増えて、余計に読みづらい感じがしますが、
規模が大きくなった際に、楽に拡張できます。

次の記事で拡張例について説明したいと思います。

参考文献

61
49
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
61
49