MRが楽しい

MRやVRについて学習したことを書き残す

VContainerのHelloWorldを試す その2(ユーザの入力を受けて実行する)

本日は VContainer の小ネタ枠です。
VContainer の HelloWorld を試したので記事に残します。
今回はユーザの入力を受けて、ロジックが実行されるケースについてです。

前回記事

以下の前回記事の続きです。
bluebirdofoz.hatenablog.com

6. 制御の反転(IoC=Inversion Of Control)

次に Unity の Button コンポーネントを例にユーザの入力を受けて、ロジックが実行されるケースを考えます。
以下のような View コンポーネントを作成します。

using UnityEngine;
using UnityEngine.UI;

public class HelloScreen : MonoBehaviour
{
    public Button HelloButton;
}

View が入力を受けた際の処理については、以下のように仕事を委譲するクラスに記述します。
IStartable は Unity の Start のライフサイクルで処理を行うためのインタフェースです。

using VContainer.Unity;

namespace MyGame
{
    // UpdateのEntryPointを作るため、IStartableのインタフェースを実装する
    public class GamePresenter : IStartable
    {
        readonly HelloWorldService helloWorldService;
        readonly HelloScreen helloScreen;

        public GamePresenter(HelloWorldService helloWorldService, HelloScreen helloScreen)
        {
            this.helloWorldService = helloWorldService;
            this.helloScreen = helloScreen;
        }

        // Startのタイミングで呼ばれる
        public void Start()
        {
            // ボタンのクリックリスナーにボタン押下時の処理を設定する
            helloScreen.HelloButton.onClick.AddListener(() =>
            {
                helloWorldService.Hello();
            });
        }
    }
}

シーン上にボタンを配置します。
Hierarchy に UI -> Button でボタンオブジェクトを作ります。

作成したボタンオブジェクトに先ほどの View コンポーネントをアタッチして Button への参照を設定します。

参照関係を解決するため、View コンポーネントもDIコンテナに登録する必要があります。
LifetimeScope を継承したクラスを以下の通り更新してDIコンテナへコンポーネントの登録を追加します。

using UnityEngine;
using VContainer;
using VContainer.Unity;

namespace MyGame
{
    public class GameLifetimeScope : LifetimeScope
    {
        [SerializeField]
        private HelloScreen helloScreen;

        protected override void Configure(IContainerBuilder builder)
        {
            // HelloWorldServiceをDIコンテナに登録する
            builder.Register<HelloWorldService>(Lifetime.Singleton);
            // GamePresenterをVContainerのEntryPointに登録する
            builder.RegisterEntryPoint<GamePresenter>();
            // HelloScreenコンポーネントをDIコンテナに登録する
            builder.RegisterComponent<HelloScreen>(helloScreen);
        }
    }
}

コンポーネントへの参照を Inspector に設定して準備は完了です。

実際にシーンを再生して動作を確認します。
ボタンを押下すると処理が呼び出されることが確認できます。