unity-scriptableobjects

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Unity ScriptableObject Architecture

Unity ScriptableObject架构

Use
ScriptableObject
assets to store shared data and decouple systems in Unity 6 — configuration, event channels, and registries that live as project assets instead of being hard-wired into scenes or singletons. Targets Unity 6 (6000.0 LTS).
使用
ScriptableObject
资源在Unity 6中存储共享数据并实现系统解耦——配置、事件通道和注册表以项目资源形式存在,而非硬编码到场景或单例中。目标版本为Unity 6 (6000.0 LTS)

When to use

适用场景

  • Use when you need designer-editable config (weapon stats, level data), to share one value between unrelated systems, to decouple senders from listeners via event channels, or to build a runtime registry of active objects — without a
    static
    /singleton manager.
  • Use when the project has
    *.asset
    data files backed by
    : ScriptableObject
    classes.
When not to use: per-instance runtime state that differs per GameObject (that belongs on a MonoBehaviour) — a ScriptableObject asset is shared by everyone who references it. Saving player progress to disk →
save-systems
. Plain DTOs that never need to be an asset can just be
[System.Serializable]
classes.
  • 当你需要设计师可编辑的配置(武器属性、关卡数据)、在无关系统间共享单个值、通过事件通道解耦发送者与监听者,或构建活动对象的运行时注册表时使用——无需
    static
    /单例管理器。
  • 当项目中存在基于
    : ScriptableObject
    类的
    *.asset
    数据文件时使用。
**不适用场景:**每个GameObject独有的实例化运行时状态(此类状态应放在MonoBehaviour中)——ScriptableObject资源会被所有引用它的对象共享。将玩家进度保存到磁盘→应使用
save-systems
。永远无需作为资源的普通DTO只需使用
[System.Serializable]
类即可。

Core workflow

核心工作流程

  1. Define the class deriving from
    ScriptableObject
    and tag it with
    [CreateAssetMenu]
    so designers can create instances from the Assets menu.
  2. Create one or more
    .asset
    instances
    in the Project window; each is a shared, named piece of data referenced by
    [SerializeField]
    fields.
  3. Reference, don't copy. MonoBehaviours hold a reference to the asset; they all see the same data, so changing the asset changes every consumer.
  4. For decoupling, model signals and shared variables as ScriptableObjects: a "FloatVariable" the HUD reads and the player writes; an "event channel" the player raises and many systems listen to. Neither side references the other.
  5. Reset runtime mutations in
    OnEnable
    if the asset is mutated during play, because edits made in the Editor at runtime persist on the asset (a frequent source of "my values changed after I played").
  6. Verify by inspecting the asset values during Play mode and confirming consumers react.
  1. 定义类:继承自
    ScriptableObject
    并标记
    [CreateAssetMenu]
    ,以便设计师能从Assets菜单创建实例。
  2. 创建一个或多个
    .asset
    实例
    :在Project窗口中创建;每个实例都是一个可命名的共享数据片段,通过
    [SerializeField]
    字段引用。
  3. 引用而非复制:MonoBehaviours持有资源的引用;它们看到的是同一数据,因此修改资源会影响所有使用者。
  4. 实现解耦:将信号和共享变量建模为ScriptableObject:比如HUD读取、玩家写入的“FloatVariable”;玩家触发、多个系统监听的“事件通道”。双方无需互相引用。
  5. 重置运行时修改:如果资源在运行时被修改,需在
    OnEnable
    中重置,因为编辑器运行时的修改会保留在资源上(这是“运行后值变了”问题的常见原因)。
  6. 验证:在Play模式下检查资源值,确认使用者做出相应反应。

Patterns

模式

1. Config/data asset

1. 配置/数据资源

csharp
using UnityEngine;

[CreateAssetMenu(fileName = "WeaponData", menuName = "Game/Weapon Data", order = 0)]
public class WeaponData : ScriptableObject
{
    public string displayName = "Pistol";
    public int    damage = 10;
    public float  fireRate = 0.25f;
    public GameObject projectilePrefab;
}
csharp
public class Weapon : MonoBehaviour
{
    [SerializeField] private WeaponData data;   // assign the shared asset in the Inspector
    private void Fire() => Debug.Log($"{data.displayName} for {data.damage}");
}
csharp
using UnityEngine;

[CreateAssetMenu(fileName = "WeaponData", menuName = "Game/Weapon Data", order = 0)]
public class WeaponData : ScriptableObject
{
    public string displayName = "Pistol";
    public int    damage = 10;
    public float  fireRate = 0.25f;
    public GameObject projectilePrefab;
}
csharp
public class Weapon : MonoBehaviour
{
    [SerializeField] private WeaponData data;   // 在Inspector中分配共享资源
    private void Fire() => Debug.Log($"{data.displayName} for {data.damage}");
}

2. Shared runtime variable (decouples producer from consumer)

2. 共享运行时变量(解耦生产者与消费者)

csharp
[CreateAssetMenu(menuName = "Game/Float Variable")]
public class FloatVariable : ScriptableObject
{
    [SerializeField] private float initialValue;
    [System.NonSerialized] public float runtimeValue;   // not saved to the asset

    private void OnEnable() => runtimeValue = initialValue;  // reset each play session
}
// Player writes playerHealth.runtimeValue; the HUD reads it — neither references the other.
csharp
[CreateAssetMenu(menuName = "Game/Float Variable")]
public class FloatVariable : ScriptableObject
{
    [SerializeField] private float initialValue;
    [System.NonSerialized] public float runtimeValue;   // 不会保存到资源中

    private void OnEnable() => runtimeValue = initialValue;  // 每次游戏会话重置
}
// 玩家写入playerHealth.runtimeValue;HUD读取该值——双方无需互相引用。

3. Creating an instance at runtime (not an asset on disk)

3. 在运行时创建实例(并非磁盘上的资源)

csharp
// For transient SO data you build in code (e.g. a generated config).
var temp = ScriptableObject.CreateInstance<WeaponData>();
temp.damage = 25;
// ...use temp...  Destroy(temp);   // clean up runtime-created instances
csharp
// 用于在代码中构建的临时SO数据(例如生成的配置)。
var temp = ScriptableObject.CreateInstance<WeaponData>();
temp.damage = 25;
// ...使用temp...  Destroy(temp);   // 清理运行时创建的实例

Pitfalls

注意事项

  • Editing an SO at runtime persists in the Editor — values you change during Play stay changed on the asset after you stop. Keep mutable runtime state in
    [NonSerialized]
    fields reset in
    OnEnable
    , or it will surprise you. (In a build, asset edits do not persist across launches.)
  • Disabled Domain Reload skips your
    OnEnable
    reset
    — with Enter Play Mode Options enabled and Reload Domain off (a Unity 6 fast-iteration setting), already-loaded SOs are not re-created when you press Play, so
    OnEnable
    never fires and
    runtimeValue
    keeps its value from the previous session. Reset explicitly from an
    ISerializationCallbackReceiver
    or a scene-load hook instead of relying on
    OnEnable
    alone.
  • Expecting per-object state — every reference points to the same asset. If two enemies need different current HP, store HP on the MonoBehaviour, not the shared SO.
  • No frame lifecycle — ScriptableObjects have
    OnEnable
    /
    OnDisable
    /
    OnDestroy
    but no
    Update
    . Don't expect per-frame callbacks.
  • Using SOs as a save file — they're authoring assets, not runtime persistence; write progress with
    save-systems
    instead.
  • Leaking
    CreateInstance
    objects
    — runtime-created instances are not garbage-collected like plain C# objects;
    Destroy
    them when done.
  • 运行时编辑SO会在编辑器中保留修改——Play模式下修改的值在停止运行后仍会保留在资源上。将可变的运行时状态放在
    [NonSerialized]
    字段中,并在
    OnEnable
    中重置,否则会出现意外情况。(在构建版本中,资源修改不会跨启动保留。)
  • 禁用域重载会跳过
    OnEnable
    重置
    ——当启用Enter Play Mode Options且关闭Reload Domain(Unity 6的快速迭代设置)时,已加载的SO在按下Play按钮时不会重新创建,因此
    OnEnable
    不会触发,
    runtimeValue
    会保留上一会话的值。此时应从
    ISerializationCallbackReceiver
    或场景加载钩子中显式重置,而非仅依赖
    OnEnable
  • 期望每个对象有独立状态——所有引用都指向同一资源。如果两个敌人需要不同的当前生命值,应将生命值存储在MonoBehaviour中,而非共享SO。
  • 没有帧生命周期——ScriptableObject有
    OnEnable
    /
    OnDisable
    /
    OnDestroy
    方法,但没有
    Update
    。不要期望每帧回调。
  • 将SO用作保存文件——它们是创作资源,而非运行时持久化工具;应使用
    save-systems
    来记录进度。
  • CreateInstance
    对象泄漏
    ——运行时创建的实例不会像普通C#对象那样被垃圾回收;使用完毕后需调用
    Destroy
    销毁它们。

References

参考资料

  • For the event-channel pattern (a
    GameEvent
    SO + listeners, type-safe payloads) and runtime sets/registries (a shared list of active enemies), read
    references/event-channels.md
    .
  • Primary docs: Unity Manual "ScriptableObject" (
    /Manual/class-ScriptableObject.html
    ) and
    ScriptReference/ScriptableObject
    ,
    ScriptReference/CreateAssetMenuAttribute
    .
  • 关于事件通道模式(
    GameEvent
    SO + 监听器、类型安全负载)和运行时集合/注册表(活动敌人的共享列表),请阅读
    references/event-channels.md
  • 官方文档:Unity手册“ScriptableObject”(
    /Manual/class-ScriptableObject.html
    )以及
    ScriptReference/ScriptableObject
    ScriptReference/CreateAssetMenuAttribute

Related skills

相关技能

  • unity-csharp-scripting
    — the MonoBehaviours that consume these assets.
  • save-systems
    — persisting state to disk (what SOs are not for).
  • card-game
    /
    rpg
    /
    survival-crafting
    — genres that lean on SO-driven data.
  • unity-csharp-scripting
    ——使用这些资源的MonoBehaviours。
  • save-systems
    ——将状态持久化到磁盘(这不是SO的用途)。
  • card-game
    /
    rpg
    /
    survival-crafting
    ——依赖SO驱动数据的游戏类型。