Flexibility

8_RuntimeVariables

Now, let's go back to the scene hierarchy and select the Boss.

You notice that the Boss’s RuntimeHealth component has an existing Scriptable Variable in its HP field. For most enemies, we leave the field empty, and HP variables will be created at runtime. However, for the Boss, we can use the same components and logic but override them with a variable that exists in the project. By doing so, we can connect the Boss’s HP variable to other elements of our game (quests, trigger events, save system, etc.).

We could also add a field for Scriptable Events like OnDeath, which would be empty for regular enemies but filled for the Boss (like our HP variable).

Because of this flexibility, we need to be careful of the order of execution. Since our existing boss Health is reset OnSceneLoaded, we need to make sure to set it to the max health on Start() and not Awake (). Indeed the execution order is the following: Awake -> OnSceneLoaded -> Start.

private void Start()
{
    //For the runtime variables, you can do this in Awake, after creating the runtime instance.
    //However, because doing this in Start works for both cases (when creating a runtime variable and referencing an existing one), it's better to do it in Start.
    //Indeed, for the Boss, its value is reset OnSceneLoaded and because of the execution order:
    //Awake-> SceneLoaded -> Start , the value should be reset to the max health.
    //Note that you could also remove Awake entirely and have its logic in Start() before these lines.
    _runtimeHpVariable.Value = _maxHealth.Value;
    _runtimeHpVariable.OnValueChanged += OnHealthChanged;
}

Therefore, putting this part of the logic on Start() makes our component work for both runtime variables and existing variables.

I hope that with this example, you can grasp the essence of runtime variables. It is not a traditional pattern, but it can work in some games. I'll let you experiment with it and see if you enjoy it.

Last updated