Search code examples
c#unity-game-enginedependency-injectioninversion-of-controlzenject

Zenject GameObject Injection


I'm using Zenject framework and I'm using multiple GameObject for a class but I don't know to do it using Zenject Container. Here's my code:

private GameObject _canvas;
private GameObject _mainWindow;
private GameObject _createAccountWindow;

void Awake()
{
    _mainWindow = GameObject.FindGameObjectWithTag("MainWindow");
    _canvas = GameObject.FindGameObjectWithTag("Canvas");
    _createAccountWindow = GameObjectExtensions.FindObject(_canvas, "CreateAccountWindow");
}

Is it possible to inject these objects from Zenject Container? If it is, how can I do that?


Solution

  • Using Zenject, those classes would be injected like this:

    [Inject]
    GameObject _canvas;
    
    [Inject]
    GameObject _mainWindow;
    
    [Inject]
    GameObject _createAccountWindow;
    

    However, when you're using DI, it usually injects based on the type, so having them all be type 'GameObject' will make this difficult.

    But if you make it something like this:

    [Inject]
    Canvas _canvas;
    
    [Inject(Id = "MainWindow")]
    RectTransform _mainWindow;
    
    [Inject(Id = "CreateAccountWindow")]
    RectTransform _createAccountWindow;
    

    Then also add ZenjectBinding components to each of these, and add a value for the Identifier property of ZenjectBinding, then it should work. (I'm assuming they are already in the scene at startup here)