3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Unity]Zenject(Extenject)の勉強用サンプルコード

Last updated at Posted at 2021-04-25

概要

Zenject(Extenject)の勉強用サンプルコードを作ってみたので共有します。

補足説明はこちらの記事をご覧ください。

Extenjectをインポートする

Package ManagerでExtenjectをインポートします。
スクリーンショット 2022-12-21 6.51.05.png

クラスを作成する

動作確認用のクラスを作成します。


using UnityEngine;
using Zenject;

/// <summary>
/// テスト用クラス
/// </summary>
public class TextDisplay : MonoBehaviour {
    [Inject] private ITest test;

    private void Start() {
        test.DebugTest();
    }
}

/// <summary>
/// インタフェース
/// </summary>
public interface ITest {
    void DebugTest();
}

/// <summary>
/// インスタンスA
/// </summary>
public class Test : ITest {
    public void DebugTest() {
        Debug.Log("初期メッセージ");
    }
}

/// <summary>
/// インスタンスB
/// </summary>
public class Test2 : ITest {
    public void DebugTest() {
        Debug.Log("機能変更後メッセージ");
    }
}

空のオブジェクトを作成してそこに貼り付けてください
スクリーンショット (80).png

MonoInstallerを作成する

Projectビュー上の任意の場所にMonoInstallerを作成します。
Create > Zenject > Mono Installer
スクリーンショット (123).png
これによってMonoInstallerのひな型が作られるのでそのコードを以下の様に書き換えます。


using UnityEngine;
using Zenject;

public class TestInstaller : MonoInstaller {
    public override void InstallBindings() {
        Container
            .Bind<ITest>()
            .To<Test>()
            .AsCached();
    }
}

SceneContextを作成する

Hierarchy上の任意の場所にSceneContextを作成します。
Zenject > Scene Context
スクリーンショット (122).png

作成されたSceneContextオブジェクトを選択し先ほど作成したTestInstallerをアタッチします。
続けてSceneContextコンポーネントのMonoInstallersにTestInstallerを登録します。
sceneContext.png

実行する

実行するとデバッグログが表示されます。
スクリーンショット (118).png

コードを変更する

コードを変更してみます。TestInstallerクラスを1行だけ変更します。

            .To<Test>()

            .To<Test2>()

実行するとデバッグログが変化して正常にコードが変更された事を確認できました。
スクリーンショット (121).png

補足

Zenjectはクラス間の密な結合を避ける為に導入されます。

今回の例では、TextDisplayのデバッグログ表示方法を変更する為にコードを書き換えましたが、1行の変更だけで実現できました。(現実的な所では「機能変更の新規インスタンスを用意する」 > 「MonoInstallerの必要部分を変更する」の手順になると思います)

従来の記述方法では依存している部分の変更を依存しているクラスの数だけやる必要があります。
規模が大きくなる程にZenjectの恩恵は大きくなっていきます。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?