A Unity design pattern to handle GetComponent caching and dependencies

The problem

In Unity, components often depend on other components. This coupling is entirely normal in a game context with Unity's component model. However, calling GetComponent is slow, so best practices suggest caching the result. The usual approach to handle this is:

class MyComponent: MonoBehaviour
{
	private Animator animator;

	private void Awake()
	{
		animator = GetComponent<Animator>();
	}
}

This approach has the following problems:

The solution

The Dependencies pattern is a better way to do this. This pattern is for you if:

The Dependency<> generic class is a small serializable class that is responsible for holding a cached component reference and finding it based on editor configuration. Let's see how it works...

Basic Use

In code, a dependency looks like this:

class MyComponent: MonoBehaviour
{
	[SerializeField]
	private Dependency<Animator> _animator;

	public Animator animator => _animator.Resolve(this);
}

In the editor, a dependency looks like this:

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/06e24bf6-5162-4c41-ab13-a2bbf4abc5e0/Untitled.png