LoginSignup
6
0

More than 1 year has passed since last update.

[Unity]VContainerをとりあえず触ってみたい方へ

Posted at

概要

Zenject(Extenject)と並んで注目されているDIライブラリVContainerを使ってみたので記事にまとめておきます。

本文

導入

まずUnityで新規プロジェクトを作成して一旦Unityを終了します。
Finder(Windowsならエクスプローラ)からプロジェクトの入ったフォルダを開きます。
プロジェクトフォルダ > Packages > manifest.json
スクリーンショット 2022-12-20 6.46.32.png
ファイルの最後の行に1行追加します。バージョンは適宜公式ページを参考に修正してください。(あと、直前の行のカンマ抜けにご注意を)

"jp.hadashikick.vcontainer" : "https://github.com/hadashiA/VContainer.git?path=VContainer/Assets/VContainer#1.12.0"

スクリーンショット 2022-12-20 6.58.13.png

VContainerの前準備ができたのでUnityを改めて起動します。このタイミングでVContainerがインポートされます。
スクリーンショット 2022-12-19 22.12.09.png

実装

以下の2つのコードを作成します。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VContainer;
using VContainer.Unity;

// 注入される側
public class GameManager : IStartable
{
    [Inject] private readonly ISampleModel _model;
    
    public void Start()
    {
        _model.PrintLog();
    }
}

// インターフェイス
public interface ISampleModel
{
    void PrintLog();
}

// 注入する側
public class SampleModel : ISampleModel
{
    public void PrintLog()
    {
        Debug.Log("TestMessage");
    }
}
using UnityEngine;
using VContainer;
using VContainer.Unity;

public class GameLifetimeScope : LifetimeScope
{
    protected override void Configure(IContainerBuilder builder)
    {
        // インスタンスを注入するクラスを指定する
        builder.RegisterEntryPoint<GameManager>(Lifetime.Singleton);
        // インスタンスをDIコンテナに登録する
        builder.Register<ISampleModel, SampleModel>(Lifetime.Singleton);
    }
}

Hierarchy上に空のオブジェクトを作成してGameLifetimeScopeを貼り付けます。
スクリーンショット 2022-12-20 8.13.57.png

SampleModelのメソッドをGameManagerのStart()で実行することが出来ました。
スクリーンショット 2022-12-20 8.11.16.png

補足

こちらの記事を参考にさせていただきました。VContainerをさらに詳しく学びたい方はぜひ!
【Unity】すごい早いという噂のDIコンテナ「VContainer」を始めて触ってみる

6
0
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
6
0