3
\$\begingroup\$

As learned about dependency injection on the internet, I found that it's something that can be done simply by the Singleton Pattern.

But there are 2 completely different views on this issue:

  • Some people say it just adds complications to project
  • Others say it is a great tool to decouple classes and code

In particular there is Zenject that is made specifically for doing dependency injection in Unity.

With this in mind, should I use dependency injection in my Unity game?

\$\endgroup\$
2
  • \$\begingroup\$ It looks like you already have your answer: "some people say it's not worthwhile, and some people say it is worthwhile" - ie. this is a matter of developer opinion. Use it if you like it and it helps you, don't use it if you dislike it or find it's too complicated. If you have questions about how to solve a particular problem with / without dependency injection, that's a more practical question to which we can offer correct, working solutions. \$\endgroup\$
    – DMGregory
    Commented Jan 13, 2019 at 18:39
  • \$\begingroup\$ I added a vote for reopening. This sort of thing is involves judgement calls guided by noting particular things about the context of the problem, so I think it falls under 'good subjective'. I'd also like to point out this related question from the Software Engineering SE: When is it not appropriate to use the dependency injection pattern? \$\endgroup\$
    – Pikalek
    Commented May 15, 2024 at 14:56

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.