1
\$\begingroup\$

I want to start using zenject in my project but I encountered an issue. From their tutorial in github page I was able to inject non monobehavior objects into each other like this.

public class MyInstaller : MonoInstaller {
     public override void InstallBindings() {
         Container.Bind<string>().FromInstance("Hello World!");
         Container.Bind<Greeter>().AsSingle().NonLazy();
         Container.Bind<BasicArmorDamageCalculator>().AsSingle().NonLazy();
     }
}

public class Greeter {

    public Greeter(String message) {
        Debug.Log("this was injected: " + message);
    }
}

But the problem is that I cannot inject objects to Monobehavior classes. Using this Installer I tried to inject Greeter to monobehavior class like this

[Zenject.Inject]
public void Construct(Greeter greeter) { 
    Debug.log(greeter);
}

And the greeter variable is null. As I understand I have to register my monobehavior class in the Installer class but It requires instantiating it while mono class is already on some game object.

What is the solution to this one?

Thanks in advance!

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

In order to have dependencies injected into MonoBehaviours that were instantiated through Instantiate(), you need to change that to:

 diContainer.InstantiatePrefab()

where diContainer is injected through [Inject]. You don't need to create an instance of Container, you can simply inject it as it is already available from the box.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .