ScriptableObjects
A ScriptableObject is a class whose instances are assets in the Project window, not components in a scene. Use them for data that many objects share and designers edit: weapon stats, enemy types, item definitions, level settings, dialogue, loot tables, audio cue sets.
Defining and creating one
using UnityEngine;
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Game/Weapon Definition")]
public class WeaponDefinition : ScriptableObject
{
[SerializeField] string displayName = "Pistol";
[SerializeField, Min(0)] int damage = 10;
[SerializeField, Min(0.01f)] float fireInterval = 0.25f;
[SerializeField] GameObject projectilePrefab;
[SerializeField] AudioClip fireSound;
public string DisplayName => displayName;
public int Damage => damage;
public float FireInterval => fireInterval;
public GameObject ProjectilePrefab => projectilePrefab;
public AudioClip FireSound => fireSound;
}- Save the script.
[CreateAssetMenu]adds a menu item. - In the Project window, right-click a folder and choose Create > Game > Weapon Definition.
- Name the asset
Shotgun, set its values in the Inspector, and duplicate it (Ctrl/Cmd+D) forRifle,Pistol... - Reference it from components with a field:
[SerializeField] WeaponDefinition weapon;.
public class Gun : MonoBehaviour
{
[SerializeField] WeaponDefinition weapon; // drag the Shotgun asset here
float nextShot;
public void TryFire()
{
if (Time.time < nextShot) return;
nextShot = Time.time + weapon.FireInterval;
// spawn weapon.ProjectilePrefab, play weapon.FireSound ...
}
}Why not just a prefab or a MonoBehaviour?
- Shared, not copied. 200 enemies referencing one
EnemyDefinitionasset share one object in memory. Two hundred[SerializeField] int maxHealthfields are two hundred copies, each a chance for a stray override. - No scene needed. Definitions live in the project, can be referenced from any scene or prefab, and can be loaded by systems like Addressables.
- Designer-friendly. One asset per item, easy to diff in version control (with Force Text), easy to add without code.
Data vs runtime state
The classic mistake: storing runtime state in a ScriptableObject.
// BAD: current ammo in a shared asset
public class WeaponDefinition : ScriptableObject { public int currentAmmo; }Every gun using that asset shares one currentAmmo, and in the editor, changes made in Play mode are written to the asset and survive after you stop. In a build, they reset when the asset is unloaded or the game restarts. Two different behaviours, both surprising. Keep definitions read-only and put runtime state in a plain C# object or a component:
using System;
using System.Collections.Generic;
// One definition asset, shared by reference.
var pistolDef = new WeaponDefinition("Pistol", Damage: 12, MagazineSize: 8);
// BAD: state stored on the shared definition.
var badA = new BadGun(pistolDef); var badB = new BadGun(pistolDef);
pistolDef.CurrentAmmo = pistolDef.MagazineSize;
badA.Fire(); badA.Fire(); badA.Fire();
Console.WriteLine(quot;bad: gun A ammo {badA.Ammo}, gun B ammo {badB.Ammo} (B never fired!)");
// GOOD: each gun keeps its own runtime state, built from the definition.
var goodA = new Gun(pistolDef); var goodB = new Gun(pistolDef);
goodA.Fire(); goodA.Fire(); goodA.Fire();
Console.WriteLine(quot;good: gun A ammo {goodA.Ammo}, gun B ammo {goodB.Ammo}");
// Lookup by id, the way a save file or network message refers to a definition.
var registry = new Dictionary<string, WeaponDefinition> { ["pistol"] = pistolDef, ["shotgun"] = new("Shotgun", 40, 2) };
foreach (var id in new[] { "shotgun", "pistol" })
Console.WriteLine(quot;{id} -> {registry[id].Name}: {registry[id].Damage} dmg, mag {registry[id].MagazineSize}");
record WeaponDefinition(string Name, int Damage, int MagazineSize)
{
public int CurrentAmmo; // the mistake, for the BadGun demo
}
class BadGun
{
readonly WeaponDefinition def;
public BadGun(WeaponDefinition d) => def = d;
public int Ammo => def.CurrentAmmo;
public void Fire() { if (def.CurrentAmmo > 0) def.CurrentAmmo--; }
}
class Gun
{
public readonly WeaponDefinition Def;
public int Ammo;
public Gun(WeaponDefinition d) { Def = d; Ammo = d.MagazineSize; }
public void Fire() { if (Ammo > 0) Ammo--; }
}bad: gun A ammo 5, gun B ammo 5 (B never fired!)
good: gun A ammo 5, gun B ammo 8
shotgun -> Shotgun: 40 dmg, mag 2
pistol -> Pistol: 12 dmg, mag 8
The registry at the end is how save files and network messages should refer to definitions: by a stable id string, never by asset name or memory address. Unity projects often keep such a list in a "database" ScriptableObject that holds every definition.
More uses
- Enum replacement: instead of
enum DamageType { Fire, Ice }, makeDamageTypea ScriptableObject. Designers can addPoisonwithout code, and each type can carry its colour, icon and resistances. - Settings assets: difficulty presets, input sensitivity defaults, audio cue sets.
- Event channels and runtime sets: assets that act as shared communication points. See ScriptableObject Event Channels.
If you need a mutable copy at runtime, clone it: Instantiate(definitionAsset) creates an independent in-memory ScriptableObject that you own (destroy it when done).
Test yourself
Where do ScriptableObject instances live?
- On GameObjects in a scene
- As assets in the project (or as runtime instances created in code)
- Only in PlayerPrefs
- Inside prefabs only
You change a ScriptableObject's field during Play mode in the editor. What happens after you stop?
- The change is reverted
- The change stays in the asset
- Unity crashes
- Only prefabs revert
What does [CreateAssetMenu] do?
- Creates an asset at startup
- Adds a Create menu entry for the ScriptableObject type
- Makes the asset read-only
- Registers it with Addressables