橋本翼(ツバサムス)

メタバースプログラマー。
UnityとUnreal Engineを専門的に扱う。
メタバース系スタートアップ企業に所属。

詳細はこちら

【Unity】ReactiveProperty(MVPパターン)とDOTweenの併用方法

Unity

ReactiveProperty(MVPパターン)とDOTweenの併用方法

TestGame概要

  • ReactiveProperty(MVPパターン)を使用
  • DOTweenを使用
  • カウントは0からスタート
  • ボタンをクリックすると「0→10→20…」と10ずつアニメーション風にカウントが増えていく
ゲーム画面

スクリプト

TestModel.cs(Model)

using UniRx;
using UnityEngine.UI;
using UnityEngine;

namespace TestGame
{
    public class TestModel : MonoBehaviour
    {
        [SerializeField]
        private Button button;//ボタン

        [SerializeField]
        private int addValue;//加える数

        [HideInInspector]
        public ReactiveProperty<int> Counter
            = new();//ReactiveProperty

        //ボタン取得用
        public Button Button { get => button; }

        public void AddCounter()
        {
            //カウントを一定数増やす
            Counter.Value += addValue;
        }
    }
}

TestView.cs(View)

using DG.Tweening;
using UnityEngine.UI;
using UnityEngine;

namespace TestGame
{
    public class TestView : MonoBehaviour
    {
        [SerializeField]
        private Text txtCount;//カウントのテキスト

        public void UpdateTxtCount(int oldValue, int newValue)
        {
            //0.5秒掛けて表示を変化させる
            txtCount.DOCounter(oldValue, newValue, 0.5f);
        }
    }
}

TestPresenter(Presenter)

using UniRx;
using UnityEngine;

namespace TestGame
{
    public class TestPresenter : MonoBehaviour
    {
        [SerializeField]
        private TestModel testModel;//Model

        [SerializeField]
        private TestView testView;//View

        void Start()
        {
            //ボタンのUnityEventであるonClickを
            //Observableに変換して購読する(監視開始)
            testModel.Button.OnClickAsObservable()
                //ボタンが押されたら
                //Observableからメッセージが発行されるが、
                //1.0秒間、2回目以降のメッセージを無視する
                .ThrottleFirst(System.TimeSpan.FromSeconds(1.0))
                //Observableから発行されたメッセージを受け取って
                .Subscribe(_
                    //カウントを一定数増やす
                    => testModel.AddCounter())
                //Sampleクラスが消えたら講読をやめる
                .AddTo(this);

            //TestModelクラスのCounterを講読する(監視開始)
            testModel.Counter
                //更新前の値と、更新後の値を取得
                .Zip(testModel.Counter.Skip(1)
                , (oldValue, newValue) => (oldValue, newValue))
                //TestModelクラスのCounterから
                //発行されたメッセージを受け取って
                .Subscribe(x
                //カウントのテキストの表示を
                //アニメーション風に更新する
                => testView.UpdateTxtCount(x.oldValue, x.newValue))
                //Sampleクラスが消えたら講読をやめる
                .AddTo(this);
        }
    }
}

お問い合わせ

    コメント

    タイトルとURLをコピーしました