Runtime Injectors
Runtime Injectors
Last updated
Runtime Injectors
Last updated
A runtime injector is a component that you attach to a game object where you want to automatically create and inject runtime variables into other components of the same object. This component improves quality of life, as you can handle dependency injection manually if needed. We show both manual and automatic injection in the runtime variable example scene & documentation.
The first step is to define the variables you want to inject.
Here are the different properties for each variable:
ID: This is the ID of the variable. It should match the ID of the attribute used later.
Runtime Variable: This field is not editable. It simply displays the variable that will be created at runtime.
Variable Template: If left null, a new variable will be created. Otherwise, a deep copy of an existing variable will be used (including all its fields). This is useful if you want to have a variable template for easy modification in one place, but still need a new instance for each prefab spawned.
Now that we have defined a variable, we need to inject it somewhere. To do this, you can add the [RuntimeInjectable]
attribute to any variable in a component on the same object (with the ID as an argument):
If you also mark the variable with [SerializeField]
, a custom inspector will be available for the variable. This is optional and only necessary if you want to see in the inspector which variables are being injected.
When the game starts, the runtime injector will create the runtime variables and automatically inject them into the designated fields. Note: This system uses reflection internally. While it employs caching to optimize the process, there is still a small performance cost. However, it's very convenient!