Inject Classes
Use Zenject Dependency Injection
There are different ways to inject classes using dependency injection. Zenject provides constructor, field, property, and method injection.
It is recommended to only use Constructor and Method Injection. Read more here
Constructor Injection
Most of your scripts will probably inherit form MonoBehaviour
so you will not be able to use constructor injection. If your class is a service or helper class that does not inherit MonoBehaviour
then you can use constructor injection.
Zenject dependency Injection will automatically provide an instance of EasyEvents into the DependencyInjectionExample
class
Zenject will inject dependencies during Unity'sAwake()
phase. Recommended to access the injected dependencies in the Start()
method instead of Awake()
Method Injection
Most of your scripts will probably inherit form MonoBehaviour
so you will not be able to use constructor injection. In that case you will need to use Method injection. There 2 ways that you can use Method Injection.
1. Have a private variable that is assigned via method injection and used throughout your class. Injected only once.
I have named the method Initialize() but you can use whatever method name you want. I have seen other people use the naming convention Constructor() since it acts like a constructor for classes that inherit from MonoBehaviour
2. Inject the class into every method that needs. Injected into every class with [Inject] attribute
Last updated