A Unity design pattern to handle
GetComponent
caching and dependencies
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:
You have to implement Awake
in every script and call GetComponent
manually
Your hierarchy structure is tightly coupled to your code. In other words, if you later decide the dependency has to live on another game object (like a child, parent or sibling), then you will have to edit your code to reflect that by calling, for example, GetComponentInParent
.
<aside> 💡 That is especially tedious for GUI code!
</aside>
Your dependencies will not get updated in edit mode (e.g. [ExecuteAlways]
). Because the dependency is cached in Awake
, even if you add the required component, your script will not notice.
The Dependencies pattern is a better way to do this. This pattern is for you if:
GetComponent
in the Awake
of all your scriptsGetComponent
oftenThe 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...
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: