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.
Code
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);
}
}
}using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Patterns.GameProgramming.ScriptableObjectVariables
{
/// <summary>
/// A single float stored as an asset (e.g. PlayerHP.asset). Writers set
/// Value, readers subscribe to OnValueChanged; neither knows the other.
/// </summary>
[CreateAssetMenu(menuName = "Variables/Float Variable")]
public class FloatVariable : ScriptableObject
{
[Tooltip("Design-time value. Every Play session starts from this.")]
[SerializeField] private float initialValue = 100f;
[Tooltip("Live value. Editable in Play Mode; reset when Play starts.")]
[SerializeField] private float runtimeValue;
public event Action<float> OnValueChanged;
public float Value
{
get => runtimeValue;
set
{
if (Mathf.Approximately(runtimeValue, value)) return;
runtimeValue = value;
OnValueChanged?.Invoke(runtimeValue);
}
}
public void ResetValue()
{
runtimeValue = initialValue;
OnValueChanged?.Invoke(runtimeValue);
}
// In a build, assets load fresh each launch, so this is enough.
private void OnEnable() => runtimeValue = initialValue;
// Typing a value into the Inspector during Play notifies every reader.
private void OnValidate() => OnValueChanged?.Invoke(runtimeValue);
#if UNITY_EDITOR
// In the editor the asset stays loaded between Play sessions, so values
// written in Play Mode would survive. Reset explicitly when Play starts.
[InitializeOnLoadMethod]
private static void HookPlayMode()
{
EditorApplication.playModeStateChanged += state =>
{
if (state != PlayModeStateChange.EnteredPlayMode) return;
foreach (string guid in AssetDatabase.FindAssets("t:FloatVariable"))
AssetDatabase.LoadAssetAtPath<FloatVariable>(AssetDatabase.GUIDToAssetPath(guid))?.ResetValue();
};
}
#endif
}
}using System;
namespace Patterns.GameProgramming.ScriptableObjectVariables
{
/// <summary>
/// A field that is either a plain constant or a shared FloatVariable,
/// picked per field in the Inspector with the UseConstant toggle.
/// </summary>
[Serializable]
public struct FloatReference
{
public bool UseConstant;
public float ConstantValue;
public FloatVariable Variable;
public FloatReference(float value)
{
UseConstant = true;
ConstantValue = value;
Variable = null;
}
public float Value => UseConstant ? ConstantValue : Variable.Value;
// Lets readers write "hp / maxHp" instead of "hp / maxHp.Value".
public static implicit operator float(FloatReference reference) => reference.Value;
}
}using UnityEngine;
using UnityEngine.UI;
namespace Patterns.GameProgramming.ScriptableObjectVariables
{
/// <summary>
/// A reader. Drop it in any scene (even one with no Player) and point
/// it at PlayerHP.asset; it updates whenever the value changes.
/// </summary>
public class HealthBar : MonoBehaviour
{
[SerializeField] private FloatVariable playerHp;
[SerializeField] private FloatReference maxHp = new FloatReference(100f);
[SerializeField] private Image fill;
private void OnEnable()
{
playerHp.OnValueChanged += Refresh;
Refresh(playerHp.Value);
}
private void OnDisable()
{
playerHp.OnValueChanged -= Refresh;
}
private void Refresh(float hp)
{
fill.fillAmount = Mathf.Clamp01(hp / maxHp);
}
}
}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 playerfield and theFindAnyObjectByType<Player>()call are gone; the bar references aFloatVariableasset instead. Updatepolling is replaced by subscribing toOnValueChangedinOnEnableand unsubscribing inOnDisable, so the bar only does work when health changes.- Max health comes from a
FloatReference, so it can be a constant or a sharedPlayerMaxHPasset without code changes. - Scene load order no longer matters: the asset exists before any scene does.
using UnityEngine;
using UnityEngine.UI;
namespace Patterns.GameProgramming.ScriptableObjectVariables
{
/// <summary>
/// Without ScriptableObject variables: the bar has to find the Player
/// itself and poll it every frame.
/// </summary>
public class HealthBar : MonoBehaviour
{
[SerializeField] private Image fill;
private Player player;
private void Start()
{
// Walks the whole scene. Returns null if the HUD loads first.
player = FindAnyObjectByType<Player>();
}
private void Update()
{
if (player == null) return;
fill.fillAmount = Mathf.Clamp01(player.CurrentHp / player.MaxHp);
}
}
}using UnityEngine;
using UnityEngine.UI;
namespace Patterns.GameProgramming.ScriptableObjectVariables
{
/// <summary>
/// With ScriptableObject variables: the bar reads a shared asset and
/// never needs to know that a Player exists.
/// </summary>
public class HealthBar : MonoBehaviour
{
[SerializeField] private Image fill;
[SerializeField] private FloatVariable playerHp;
[SerializeField] private FloatReference maxHp = new FloatReference(100f);
private void OnEnable()
{
playerHp.OnValueChanged += Refresh;
Refresh(playerHp.Value);
}
private void OnDisable()
{
playerHp.OnValueChanged -= Refresh;
}
private void Refresh(float hp)
{
fill.fillAmount = Mathf.Clamp01(hp / maxHp);
}
}
}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
- 01Keep a serialized
initialValueseparate from the runtime value, and reset the runtime value when Play Mode starts. Do not rely onOnEnablealone when Enter Play Mode Options skips the domain reload. - 02Raise
OnValueChangedonly when the value really changes, and subscribe inOnEnableand unsubscribe inOnDisable, exactly as with any C# event. - 03Use
FloatReference(orIntReference) for tuning fields so designers choose per field between a constant and a shared variable. - 04Call
OnValueChangedfromOnValidateso values typed directly into the Inspector during Play also notify readers. - 05Combine with ScriptableObject events: the variable holds state, the event channel announces moments such as
PlayerDied.