Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zenject GameObject Injection

Tags:

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?

like image 428
Masoud Darvishian Avatar asked Sep 24 '16 10:09

Masoud Darvishian


People also ask

How does Zenject work?

In Zenject, dependency mapping is done by adding bindings to something called a container. The container should then 'know' how to create all the object instances in your application, by recursively resolving all dependencies for a given object.

What is Property injection?

Property injection is a type of dependency injection where dependencies are provided through properties. Visit the Dependency Injection chapter to learn more about it. Let's understand how we can perform property injection using Unity container. Consider the following example classes.

What is dependency injection unity?

Dependency injection is a design pattern and an implementation of the inversion of control design principle. It helps simplify and automate the wiring of components in complex applications. It helps achieve component isolation, something that is important for unit-testing.

What is dependency injection stack overflow?

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.


1 Answers

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)

like image 171
Steve Vermeulen Avatar answered Sep 25 '22 16:09

Steve Vermeulen