5

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?

Masoud Darvishian
  • 3,754
  • 4
  • 33
  • 41

1 Answers1

4

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)

Steve Vermeulen
  • 1,406
  • 1
  • 19
  • 25
  • 2
    Is there a way to inject a game object with id via constructor or method injection, not property injection? – Nikolai Aug 16 '20 at 13:51