Automatic Injection

8_RuntimeVariables

In this scene, we demonstrate an example of automatic injection. Instead of manually passing the runtime variables to other components, we will use the Runtime Injector. Select enemy_runtime_autoInjection in the scene.

You can see that this component will create and inject two variables: hp and speed. For the hp variable, it will create a deep copy of the example variable example_float_enemyHealthTemplate. This is useful because we can predefine a max value.

Next, it will inject the hp variable into both the RuntimeHealthInjected component and the HealthBarSpriteAutoInjection component.

For the speed variable, it will create a brand-new variable (without a template) and inject it into EnemyMovementInjected.cs.

If we look at the code, the fields to be injected are simply marked with the [RuntimeInjectable] attribute. Here is what RuntimeHealthInjected.cs looks like:

public class RuntimeInjectedHealth : MonoBehaviour
{
    [Tooltip("This field will be injected at runtime")] 
    [SerializeField]
    [RuntimeInjectable("hp")] 
    private FloatVariable _runtimeHpVariable;

    [SerializeField] private FloatReference _maxHealth;
    
    private void Start()
    {
        _runtimeHpVariable.Value = _maxHealth.Value;
        _runtimeHpVariable.OnValueChanged += OnHealthChanged;
    }

    private void OnDisable()
    {
        _runtimeHpVariable.OnValueChanged -= OnHealthChanged;
    }

    private void OnHealthChanged(float newValue)
    {
        if (newValue <= 0f)
            gameObject.SetActive(false);
    }

    //In this example, this is called when the enemy collides with the Player.
    public void TakeDamage(int amount) => _runtimeHpVariable.Add(-amount);
}

As you can see, this approach eliminates much of the manual work previously required, such as creating and injecting the variables.

Note: The RuntimeInjector calls its Awake method before the default components. This means that other components can directly access the injected variables in their Awake methods (as shown in RuntimeHealthInjected.cs).

Last updated