I think Unity is already pretty dependency-injection compatible out-of-the-box.
What are the usual ways to obtain dependencies to other behaviours in a MonoBehaviour?
- The
GetComponent
method, either on the object itself or on objects it references
- Public variables which reference components and can be assigned in the inspector
Both of these features can be used with interfaces or abstract classes instead of implementing classes (In that case GetComponent
will return the first component which implements said interface/class).
When you have an object which creates other objects, then the DI-compliant solution would be to pass a Factory to that object instead of having it do
new ClassName()
. But when you have an Unity GameObject which creates other Unity GameObjects, then the usual way to do this is by using the Instantiate
method with a prefab which you assign to a public variable in the inspector. This is also a case of dependency injection because the code which calls Instantiate
doesn't need to know anything about the prefab in order to instantiate it.