←All patterns
Game Programming

ScriptableObject Variables

Store shared values like player health in assets, so writers and readers meet at the data instead of at each other.

What Is It?

A ScriptableObject variable is an asset that holds one value. PlayerHP.asset is a FloatVariable with a Value property and an OnValueChanged event. It lives in the Project window, not in any scene, so any component in any scene or prefab can reference it through a normal Inspector field.

The player writes to the asset when it takes damage. The health bar, the low-health vignette and the heartbeat audio read from the same asset. None of them references the Player, and the Player references none of them. The asset sits in the middle, much like an Observer subject that has been moved out of the scene and into the project.

A companion type, FloatReference, makes the idea flexible: it is a small serializable struct with a UseConstant toggle. A designer can type 100 for a one-off enemy, or drag in PlayerMaxHP.asset when several systems must agree on the number, and the code reading maxHp.Value does not care which.

When Is It Used?

Use it for game-wide values that several unrelated systems need: player health, score, ammo, currency, current wave, master volume. These are exactly the values people usually reach for a singleton or FindObjectOfType to get.

It shines in scene-heavy projects. The HUD can live in its own additively loaded scene and still show the player health, because both scenes point at the same asset instead of at each other. Prefabs can be tested in an empty scene by editing the asset by hand.

Avoid it for per-instance state. Fifty enemies cannot share one EnemyHP.asset, because every enemy would write to the same number. Use a normal field there, or a runtime set if you need to track them together.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

ScriptableObject Variables Pattern
PlayerHP100modeEditrefs to Player0sessions0
■ Edit Mode
Player
writes
hp.Value -= dmg
PlayerHP.asset
FloatVariable
Value100
HealthBar
not running
Vignette
not running
Heartbeat
not running
♥
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ ScriptableObjectVariables ›Player.cs
using UnityEngine;

namespace Patterns.GameProgramming.ScriptableObjectVariables
{
    /// <summary>
    /// The writer. It only knows the PlayerHP asset, not the health bar,
    /// the vignette or the audio that react to it.
    /// </summary>
    public class Player : MonoBehaviour
    {
        [SerializeField] private FloatVariable hp;
        [SerializeField] private FloatReference maxHp = new FloatReference(100f);

        private void Start() => hp.Value = maxHp;

        public void TakeDamage(float amount)
        {
            hp.Value = Mathf.Max(0f, hp.Value - amount);
        }

        public void Heal(float amount)
        {
            hp.Value = Mathf.Min(maxHp, hp.Value + amount);
        }
    }
}
4 files · namespace Patterns.Game Programming.ScriptableObjectVariablesC# · UTF-8 · LF

Before & After

Real-world smell: a health bar that searches the scene for the player. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

HealthBar calls FindAnyObjectByType<Player>() in Start and then reads player.CurrentHp in Update every frame. It works in the main scene, but only because the player happens to exist before the HUD starts.

Load the HUD additively, spawn the player late or open the HUD prefab in a test scene, and player is null, so the bar silently stops updating. The bar also polls every frame even when nothing changed, and it cannot exist without a Player class in the project.

✓ What changed

  • The Player player field and the FindAnyObjectByType<Player>() call are gone; the bar references a FloatVariable asset instead.
  • Update polling is replaced by subscribing to OnValueChanged in OnEnable and unsubscribing in OnDisable, so the bar only does work when health changes.
  • Max health comes from a FloatReference, so it can be a constant or a shared PlayerMaxHP asset without code changes.
  • Scene load order no longer matters: the asset exists before any scene does.
HealthBar.Before.cs → HealthBar.After.cs+13/−9
11 using UnityEngine;
22 using UnityEngine.UI;
33
44 namespace Patterns.GameProgramming.ScriptableObjectVariables
55 {
66 /// <summary>
7− /// Without ScriptableObject variables: the bar has to find the Player
8− /// itself and poll it every frame.
7+ /// With ScriptableObject variables: the bar reads a shared asset and
8+ /// never needs to know that a Player exists.
99 /// </summary>
1010 public class HealthBar : MonoBehaviour
1111 {
1212 [SerializeField] private Image fill;
1313
14− private Player player;
14+ [SerializeField] private FloatVariable playerHp;
15+ [SerializeField] private FloatReference maxHp = new FloatReference(100f);
1516
16− private void Start()
17+ private void OnEnable()
1718 {
18− // Walks the whole scene. Returns null if the HUD loads first.
19− player = FindAnyObjectByType<Player>();
19+ playerHp.OnValueChanged += Refresh;
20+ Refresh(playerHp.Value);
2021 }
2122
22− private void Update()
23+ private void OnDisable()
2324 {
24− if (player == null) return;
25+ playerHp.OnValueChanged -= Refresh;
26+ }
2527
26− fill.fillAmount = Mathf.Clamp01(player.CurrentHp / player.MaxHp);
28+ private void Refresh(float hp)
29+ {
30+ fill.fillAmount = Mathf.Clamp01(hp / maxHp);
2731 }
2832 }
2933 }

Advantages & Disadvantages

+ Advantages

  • Writers and readers are fully decoupled; neither needs a scene reference to the other.
  • Designers can watch and change live values in the Inspector during Play Mode, and every reader reacts.
  • Systems can be built and tested in isolation; a test scene only needs the asset, not the whole player.

− Disadvantages

  • In the editor, values changed in Play Mode persist after you stop playing, because the asset stays loaded. Without a reset, the next session starts with yesterday’s health.
  • Many tiny assets can clutter the project, and it is less obvious from code who writes a value.
  • Any script can write to the asset; nothing in the type system stops a stray UI script from changing PlayerHP.

Tips

  1. 01Keep a serialized initialValue separate from the runtime value, and reset the runtime value when Play Mode starts. Do not rely on OnEnable alone when Enter Play Mode Options skips the domain reload.
  2. 02Raise OnValueChanged only when the value really changes, and subscribe in OnEnable and unsubscribe in OnDisable, exactly as with any C# event.
  3. 03Use FloatReference (or IntReference) for tuning fields so designers choose per field between a constant and a shared variable.
  4. 04Call OnValueChanged from OnValidate so values typed directly into the Inspector during Play also notify readers.
  5. 05Combine with ScriptableObject events: the variable holds state, the event channel announces moments such as PlayerDied.