Across the Unity development community, an architectural pattern once sparked widespread adoption: using ScriptableObject assets as dynamic runtime data containers. This approach gained massive popularity following Ryan Hipple's iconic presentation at Unite Austin 2017 on game architecture with ScriptableObject.
On paper, the strategy appears remarkably elegant. Instead of constructing monolithic Singleton managers to host shared states, developers create project assets such as PlayerHealthSO, GameScoreSO, or InventorySO. Any combat script needing to apply damage simply references the asset in the Inspector and executes playerHealthSO.value -= damage. The UI layer references the exact same asset to refresh health bars. Scene-level dependencies seemingly dissolve, providing a decoupled and modular developer experience.
However, once this architecture is deployed into long-term commercial production with numerous scenes, complex mechanics, and multi-developer teams, critical friction points emerge. Designer-balanced values get silently overwritten after exiting Play Mode, game behavior diverges wildly between development machines and production mobile builds, and multiple enemy instances sharing an asset inadvertently drain each other's health.
This article examines the underlying memory and serialization mechanics of ScriptableObject, exposes the technical traps of using it as a runtime state container, and outlines an architectural separation between immutable blueprints and transient session data.
1. The Nature of ScriptableObject: Disk Asset, Not Scene Instance
To understand why using ScriptableObject for mutable runtime data introduces architectural risks, we must examine its lifecycle within the Unity Engine.
When attaching a MonoBehaviour to a Prefab, calling Instantiate() allocates a distinct instance in the active scene with dedicated memory. Two enemy entities spawned from the same Prefab possess independent MonoBehaviour instances; modifying health on the first has zero impact on the second.
In contrast, a ScriptableObject is an asset stored permanently on disk (typically as a YAML .asset file). When ten components reference a ScriptableObject, they do not hold ten independent copies. They point to the exact same memory address loaded into RAM by the engine.
flowchart LR
subgraph SceneEntities["Scene Entities"]
E1["Enemy Instance A"]
E2["Enemy Instance B"]
end
subgraph BrokenContainer["Trap: SO as State Container"]
SO["Single Asset SO<br/>Holds mutable currentHealth"]
end
E1 -->|"1. Takes 20 damage"| SO
SO -.->|"2. Inadvertently drains"| E2
This structural difference transforms ScriptableObject into a double-edged sword when used to manage dynamic, mutable gameplay state.
2. Four Critical Pitfalls of Runtime ScriptableObject Containers
Treating ScriptableObject as a session data store introduces four major production traps:
1. Runtime State Contaminates Disk Assets (The Dirty Asset Bug)
In the Unity Editor, when a script mutates a field on a ScriptableObject during Play Mode, Unity marks the asset as dirty. If a developer saves the scene or project, those transient gameplay values are serialized permanently into the .asset file on disk.
Consider a common scenario: a programmer tests combat mechanics and temporarily buffs weapon damage from 20 to 500 in Play Mode to clear enemies quickly. Upon exiting Play Mode, 500 remains permanently baked into the asset. The following morning, the game designer discovers the entire weapon balancing table is corrupted. Tracking down this mutation wastes valuable time and creates merge conflicts in version control.
2. Behavioral Discrepancies Between Editor and Production Builds
This discrepancy is particularly insidious because it makes bugs difficult to reproduce:
-
In the Editor: Runtime mutations on a
ScriptableObjectcan persist across Play Mode sessions and write directly to disk files. - In Production Builds (iOS, Android, Standalone): Project assets are packed into compressed read-only binary archives (Data archives or AssetBundles). The operating system prohibits writing to these packaged assets at runtime. Consequently, mutations only exist temporarily in volatile RAM for the active session. When the player restarts the application, all fields revert to initial build values.
As a result, QA testers on mobile devices report: "Player item counts fail to persist after restarting the app", while developers testing in the Unity Editor observe: "Everything saves as expected". Two environments produce contradictory results because ScriptableObject serialization was never intended as a runtime storage engine.
3. The Unintended Shared State Trap
Suppose a dungeon level spawns 50 skeletons of the same type. If their scripts all reference an asset named SkeletonDataSO containing public int currentHp:
- The instant Skeleton #1 gets struck by an arrow and loses 15 HP, all remaining 49 skeletons on the map simultaneously lose 15 HP.
- All enemies share a single health pool because they read and write to one common memory reference.
To bypass this issue, developers often invoke Instantiate(skeletonDataSO) at spawn time to clone a runtime copy in RAM. However, this introduces another drawback: native memory leaks. Assets created via Instantiate or CreateInstance during runtime are not automatically collected by the C# Garbage Collector like pure C# objects. If developers forget to call Destroy(clonedSO) when the enemy is killed, that unmanaged C++ memory lingers until the scene unloads, causing progressive memory leak issues on mobile devices.
4. Erasing the Boundary Between Blueprint and Session State
From a data architecture perspective:
- Blueprint (Config Data): An immutable template defining an entity's identity and constants: base attributes, armor ratings, progression curves, visual asset references.
- Session State (Runtime Data): The transient condition of a specific instance during an active match: remaining hit points, active debuff timers, current grid position.
Conflating Session State with Blueprints violates the Single Responsibility Principle, turning clean shared definitions into volatile global state.
3. Recommended Architecture: Separating Blueprints from Runtime Models
The robust approach for commercial production is returning ScriptableObject to its core strength: An Immutable Blueprint. Dynamic session state is delegated entirely to pure C# classes.
flowchart LR
subgraph BlueprintLayer["Data Blueprint"]
SO["ScriptableObject Blueprint<br/>Base Stats: Health, Armor, Damage"]
end
subgraph RuntimeLayer["Session State Model"]
R1["Runtime Session A<br/>Current HP: 80 out of 100"]
R2["Runtime Session B<br/>Current HP: 100 out of 100"]
end
SO -->|"Populates base stats"| R1
SO -->|"Populates base stats"| R2
Architectural Principles:
-
ScriptableObjects Remain Immutable: Use
[SerializeField] privatefields paired with public getters. Never expose public setters or mutation methods on shared asset definitions. -
Instantiate Pure C# State on Spawn: When an entity spawns, it reads initial values from the
ScriptableObjectblueprint to construct a dedicated C# state object. All damage calculations and buff updates occur strictly within this session instance. -
Automated Lifecycle Cleanup: Because the runtime state is a plain C# object (not inheriting from
UnityEngine.Object), it is governed by the standard Garbage Collector. When the entity is destroyed and references drop, memory is collected automatically without risk of native asset leaks.
4. Code Demonstration: From Shared State Trap to Decoupled Tiers
To demonstrate the difference, let us examine an enemy attribute system in an action RPG.
In this system, multiple enemies spawn from a shared archetype. Each active enemy must manage its current hit points independently, compute damage through armor, and trigger death events without interfering with peer entities.
Flawed Pattern: Mutable State on ScriptableObject
Below is the fragile approach: a single ScriptableObject holding both maximum and current hit points.
using UnityEngine;
// Asset saved in project: Assets/Data/GoblinStats.asset
public class FlawedEnemyStatsSO : ScriptableObject
{
public string enemyName = "Goblin";
public int maxHealth = 100;
// Architectural trap: Storing mutable runtime state on shared asset
public int currentHealth = 100;
public void TakeDamage(int damage)
{
currentHealth -= damage;
Debug.Log($"{enemyName} HP: {currentHealth}");
}
}
public class FlawedEnemyEntity : MonoBehaviour
{
// Multiple scene instances drag and drop this same asset
public FlawedEnemyStatsSO sharedStats;
public void OnHit(int damage)
{
if (sharedStats != null)
{
// Defect: Damaging this unit damages all units sharing the asset
sharedStats.TakeDamage(damage);
}
}
}
Running this code links every enemy's vitality together. In the Editor, stopping Play Mode can leave currentHealth damaged permanently, altering project balance files.
Decoupled Pattern: Immutable Blueprint and Pure C# Session State
We refactor the architecture by decoupling responsibilities through the IEnemyBlueprint interface:
-
IEnemyBlueprint: The contract governing immutable attribute queries. -
EnemyBlueprintSO: ImplementsIEnemyBlueprinton aScriptableObjectasset, safeguarding constants in read-only mode. -
EnemyBlueprintData: A pure C# implementation ofIEnemyBlueprintenabling automated unit testing without engine dependencies. -
EnemyRuntimeSession: A pure C# class tracking transient health and processing damage logic. -
EnemyController: A lightweightMonoBehaviourserving as the engine bridge, owning an isolatedEnemyRuntimeSession.
using System;
using UnityEngine;
// 1. BLUEPRINT CONTRACT & ASSET: Immutable configuration data (Read-Only)
public interface IEnemyBlueprint
{
string EnemyName { get; }
int MaxHealth { get; }
int BaseDamage { get; }
int Armor { get; }
}
public class EnemyBlueprintSO : ScriptableObject, IEnemyBlueprint
{
[SerializeField] private string enemyName = "Goblin";
[SerializeField] private int maxHealth = 100;
[SerializeField] private int baseDamage = 15;
[SerializeField] private int armor = 5;
public string EnemyName => enemyName;
public int MaxHealth => maxHealth;
public int BaseDamage => baseDamage;
public int Armor => armor;
}
// Pure C# data wrapper for automated testing without Unity Editor
public class EnemyBlueprintData : IEnemyBlueprint
{
public string EnemyName { get; }
public int MaxHealth { get; }
public int BaseDamage { get; }
public int Armor { get; }
public EnemyBlueprintData(string name, int maxHp, int damage, int armor)
{
EnemyName = name;
MaxHealth = maxHp;
BaseDamage = damage;
Armor = armor;
}
}
// 2. RUNTIME STATE LAYER: Pure C# domain logic independent of UnityEngine
public class EnemyRuntimeSession
{
private readonly IEnemyBlueprint _blueprint;
public int CurrentHealth { get; private set; }
public bool IsDead => CurrentHealth <= 0;
public event Action<int, int> OnHealthChanged; // (current, max)
public event Action OnDied;
public EnemyRuntimeSession(IEnemyBlueprint blueprint)
{
_blueprint = blueprint ?? throw new ArgumentNullException(nameof(blueprint));
CurrentHealth = _blueprint.MaxHealth;
}
public int TakeDamage(int rawDamage)
{
if (IsDead || rawDamage <= 0) return 0;
int netDamage = Math.Max(1, rawDamage - _blueprint.Armor);
CurrentHealth = Math.Max(0, CurrentHealth - netDamage);
OnHealthChanged?.Invoke(CurrentHealth, _blueprint.MaxHealth);
if (IsDead)
{
OnDied?.Invoke();
}
return netDamage;
}
}
// 3. UNITY BRIDGE LAYER: Thin MonoBehaviour hosting isolated session state
public class EnemyController : MonoBehaviour
{
[SerializeField] private EnemyBlueprintSO blueprint;
// Each scene GameObject owns an independent runtime session
public EnemyRuntimeSession RuntimeSession { get; private set; }
private void Awake()
{
if (blueprint != null)
{
Initialize(blueprint);
}
}
public void Initialize(IEnemyBlueprint config)
{
RuntimeSession = new EnemyRuntimeSession(config);
RuntimeSession.OnHealthChanged += HandleHealthChanged;
RuntimeSession.OnDied += HandleDied;
}
private void HandleHealthChanged(int currentHp, int maxHp)
{
Debug.Log($"[View] HP: {currentHp}/{maxHp}");
}
private void HandleDied()
{
Debug.Log($"[View] Died. Triggering death VFX.");
}
}
flowchart LR
subgraph BlueprintAsset["ScriptableObject (Single Shared Asset)"]
SO["EnemyBlueprintSO<br/>MaxHealth: 100 | Armor: 5"]
end
subgraph SpawnedInstances["Scene Instances"]
subgraph EntityA["Goblin #1"]
CA["EnemyController A"]
SA["EnemyRuntimeSession A<br/>CurrentHealth: 70/100"]
end
subgraph EntityB["Goblin #2"]
CB["EnemyController B"]
SB["EnemyRuntimeSession B<br/>CurrentHealth: 100/100"]
end
end
SO -->|"Injects base stats"| SA
SO -->|"Injects base stats"| SB
CA -->|"Owns exclusively"| SA
CB -->|"Owns exclusively"| SB
Automated Unit Testing (NUnit Runner)
By decoupling logic and data from engine lifecycles, health deductions and multi-instance independence can be verified in milliseconds using NUnit:
using NUnit.Framework;
[TestFixture]
public class ScriptableObjectRuntimeContainerTests
{
[Test]
public void TwoEntities_SharingSameBlueprint_MaintainIndependentRuntimeHealth()
{
// Arrange: Single blueprint definition (Max HP 100, Armor 5)
var blueprint = new EnemyBlueprintData("Goblin", maxHp: 100, damage: 15, armor: 5);
// Instantiate two combat sessions from the same blueprint
var enemyA = new EnemyRuntimeSession(blueprint);
var enemyB = new EnemyRuntimeSession(blueprint);
// Act: Apply 35 damage to Enemy A (reduced to 30 after 5 armor)
int damageDealtToA = enemyA.TakeDamage(35);
// Assert: Enemy A loses health; Enemy B remains completely unaffected
Assert.AreEqual(30, damageDealtToA);
Assert.AreEqual(70, enemyA.CurrentHealth);
Assert.AreEqual(100, enemyB.CurrentHealth);
Assert.IsFalse(enemyA.IsDead);
Assert.IsFalse(enemyB.IsDead);
}
[Test]
public void FatalDamage_ToEntityA_KillsEntityA_WhileEntityBRemainsAlive()
{
// Arrange
var blueprint = new EnemyBlueprintData("Skeleton", maxHp: 50, damage: 20, armor: 0);
var enemyA = new EnemyRuntimeSession(blueprint);
var enemyB = new EnemyRuntimeSession(blueprint);
bool enemyADied = false;
bool enemyBDied = false;
enemyA.OnDied += () => enemyADied = true;
enemyB.OnDied += () => enemyBDied = true;
// Act: Deliver lethal blow to Enemy A
enemyA.TakeDamage(100);
// Assert
Assert.AreEqual(0, enemyA.CurrentHealth);
Assert.IsTrue(enemyA.IsDead);
Assert.IsTrue(enemyADied);
Assert.AreEqual(50, enemyB.CurrentHealth);
Assert.IsFalse(enemyB.IsDead);
Assert.IsFalse(enemyBDied);
}
[Test]
public void BlueprintData_RemainsImmutable_AfterIntenseCombatCalculations()
{
// Arrange
var blueprint = new EnemyBlueprintData("BossDragon", maxHp: 1000, damage: 80, armor: 25);
var session = new EnemyRuntimeSession(blueprint);
// Act: Apply heavy combat cycles
session.TakeDamage(200);
session.TakeDamage(500);
// Assert: Underlying blueprint attributes remain completely untouched
Assert.AreEqual(1000, blueprint.MaxHealth);
Assert.AreEqual(80, blueprint.BaseDamage);
Assert.AreEqual(25, blueprint.Armor);
Assert.AreEqual("BossDragon", blueprint.EnemyName);
}
}
5. Engineering Trade-offs: Comparing Three Data Strategies
| Evaluation Metric | Direct Mutable SO (Ryan Hipple Pattern) | Runtime SO Cloning (Instantiate(SO)) |
Decoupled: SO Blueprint + Pure C# State |
|---|---|---|---|
| Memory Allocation | Writes to asset files in Editor; volatile RAM in Build. | Clones runtime SO instance into RAM. | SO stays on disk; Session State lives on Managed Heap. |
| Dirty Asset Risk | Extremely high: risks corrupting designer balancing files. | Safe from disk asset corruption. | Zero risk: SO fields are strictly read-only. |
| Leak Management | No memory leaks, but severe shared-state logic defects. | Risk of native C++ leaks if Destroy() is missed on clones. |
100% automated via standard C# Garbage Collection. |
| Automated Testing | Tied to Unity Editor serialization and play-mode runtime. | Heavy setup, requires instantiating UnityEngine.Object. |
Extremely fast: executes hundreds of test cases in milliseconds. |
| Code Complexity | Low initial boilerplate, but severe maintenance debt later. | Moderate, requires tracking cloned asset lifecycles. | Requires state classes, but delivers deterministic boundaries. |
6. Practical Takeaways
The answer to "Should you use ScriptableObjects as runtime data containers?" is: No, not for mutable per-instance gameplay state.
Keep three boundaries clear in your data architecture:
- ScriptableObjects are Blueprints, Not States: Reserve them for immutable constants balanced by designers.
- Delegate Session State to Pure C#: Every spawned GameObject should own an independent C# state instance to eliminate shared mutations and native memory leaks.
-
Segregate Persistence Systems: When player progress must survive application restarts, route data through a dedicated Save/Load pipeline (JSON, SQLite, or binary serialization), rather than relying on
ScriptableObjectasset serialization.

Top comments (0)