Basics of Dependencies in Unity

October 19, 2020

Dependencies

Unity


Title: Dependencies in Unity
By: Infallible Code
Youtube - Tutorial
Description: Covers the basics of dependencies in programming, with a focus on them within Unity and how they deal with expensive method calls.


Overview

This tutorial nicely breaks down dependencies in programming in general in a very basic and understandable way. This is good for defining it well at the foundational level. It also covers some of Unity's more expensive method calls and the different ways to cache these results, as well as the different ways to organize and manage dependencies within Unity specifically.

Notes

Dependency: When one object relies on another to function.
The initial example in this tutorial nicely shows how improper code can also hide dependencies. Since they were using FindObjectOfType in the Update method (an extremely expensive and inefficient process), it could be lost that that class was dependent on the Inventory object. Creating a private variable at the class level to hold that data and caching it in the Awake method makes it more much clear, exposing the dependency on the Inventory object.

Dependency Management Techniques

Dependency management techniques are just the ways your classes are accessed by the objects they depend on. There are two major groups for this: internal resolution and external resolution.

Internal Resolution

When an object is responsible for resolving its own dependencies
Accomplished by:

  • Instantiating new instances
  • Using factories or the factory method
  • Using Unity's built in getters (i.e. GetComponent, FindByComponent)

External Resolution

When an object receives its dependencies from another object
Accomplished by:

  • Constructor parameters
  • Public fields and setter methods
  • Serialized fields

Examples of Using (Or Not Using) Different Methods

Some examples covered:

  • Do NOT use GetObjectOfType if you will have multiple objects of that type
  • For very simple cases, the external serialized field option is common practice
  • Serialized field does not work well if object is loaded dynamically
  • Dynamically loaded objects can usually use an initialization method that acts like a constructor
  • Dynamically loaded objects can also use constructors if they are normal C# classes, but monobehaviours do NOT support constructors

Extenject

Dependency injection is just another word for external resolution. Extenject is a dependency injection framework that manages all the dependencies across your entire project. Extenject can be very useful, but can quickly overcomplicate smaller and simpler projects.

Comments

Popular posts from this blog

Online Multiplayer Networking Solution Tutorial Using Unity and Mirror - Tutorial by: Jason Weimann

Exporting FBX from Houdini with Color

Houdini Assignment - Fuse and Group