TExcelTAD
Home › Unity with C# › ScriptableObjects

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

csharp
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;
}
  1. Save the script. [CreateAssetMenu] adds a menu item.
  2. In the Project window, right-click a folder and choose Create > Game > Weapon Definition.
  3. Name the asset Shotgun, set its values in the Inspector, and duplicate it (Ctrl/Cmd+D) for Rifle, Pistol...
  4. Reference it from components with a field: [SerializeField] WeaponDefinition weapon;.
csharp
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 EnemyDefinition asset share one object in memory. Two hundred [SerializeField] int maxHealth fields 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.

csharp
// 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:

csharp · try it yourself
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 }, make DamageType a ScriptableObject. Designers can add Poison without 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?

  1. On GameObjects in a scene
  2. As assets in the project (or as runtime instances created in code)
  3. Only in PlayerPrefs
  4. Inside prefabs only

You change a ScriptableObject's field during Play mode in the editor. What happens after you stop?

  1. The change is reverted
  2. The change stays in the asset
  3. Unity crashes
  4. Only prefabs revert

What does [CreateAssetMenu] do?

  1. Creates an asset at startup
  2. Adds a Create menu entry for the ScriptableObject type
  3. Makes the asset read-only
  4. Registers it with Addressables