unity-scriptableobjects
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUnity ScriptableObject Architecture
Unity ScriptableObject架构
Use 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)。
ScriptableObjectWhen 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 /singleton manager.
static - Use when the project has data files backed by
*.assetclasses.: ScriptableObject
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 → . Plain DTOs that never need to be an asset can just be
classes.
save-systems[System.Serializable]- 当你需要设计师可编辑的配置(武器属性、关卡数据)、在无关系统间共享单个值、通过事件通道解耦发送者与监听者,或构建活动对象的运行时注册表时使用——无需/单例管理器。
static - 当项目中存在基于类的
: ScriptableObject数据文件时使用。*.asset
**不适用场景:**每个GameObject独有的实例化运行时状态(此类状态应放在MonoBehaviour中)——ScriptableObject资源会被所有引用它的对象共享。将玩家进度保存到磁盘→应使用。永远无需作为资源的普通DTO只需使用类即可。
save-systems[System.Serializable]Core workflow
核心工作流程
- Define the class deriving from and tag it with
ScriptableObjectso designers can create instances from the Assets menu.[CreateAssetMenu] - Create one or more instances in the Project window; each is a shared, named piece of data referenced by
.assetfields.[SerializeField] - Reference, don't copy. MonoBehaviours hold a reference to the asset; they all see the same data, so changing the asset changes every consumer.
- 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.
- Reset runtime mutations in 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").
OnEnable - Verify by inspecting the asset values during Play mode and confirming consumers react.
- 定义类:继承自并标记
ScriptableObject,以便设计师能从Assets菜单创建实例。[CreateAssetMenu] - 创建一个或多个实例:在Project窗口中创建;每个实例都是一个可命名的共享数据片段,通过
.asset字段引用。[SerializeField] - 引用而非复制:MonoBehaviours持有资源的引用;它们看到的是同一数据,因此修改资源会影响所有使用者。
- 实现解耦:将信号和共享变量建模为ScriptableObject:比如HUD读取、玩家写入的“FloatVariable”;玩家触发、多个系统监听的“事件通道”。双方无需互相引用。
- 重置运行时修改:如果资源在运行时被修改,需在中重置,因为编辑器运行时的修改会保留在资源上(这是“运行后值变了”问题的常见原因)。
OnEnable - 验证:在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 instancescsharp
// 用于在代码中构建的临时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 fields reset in
[NonSerialized], or it will surprise you. (In a build, asset edits do not persist across launches.)OnEnable - Disabled Domain Reload skips your 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
OnEnablenever fires andOnEnablekeeps its value from the previous session. Reset explicitly from anruntimeValueor a scene-load hook instead of relying onISerializationCallbackReceiveralone.OnEnable - 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/OnDisablebut noOnDestroy. Don't expect per-frame callbacks.Update - Using SOs as a save file — they're authoring assets, not runtime persistence; write
progress with instead.
save-systems - Leaking objects — runtime-created instances are not garbage-collected like plain C# objects;
CreateInstancethem when done.Destroy
- 运行时编辑SO会在编辑器中保留修改——Play模式下修改的值在停止运行后仍会保留在资源上。将可变的运行时状态放在字段中,并在
[NonSerialized]中重置,否则会出现意外情况。(在构建版本中,资源修改不会跨启动保留。)OnEnable - 禁用域重载会跳过重置——当启用Enter Play Mode Options且关闭Reload Domain(Unity 6的快速迭代设置)时,已加载的SO在按下Play按钮时不会重新创建,因此
OnEnable不会触发,OnEnable会保留上一会话的值。此时应从runtimeValue或场景加载钩子中显式重置,而非仅依赖ISerializationCallbackReceiver。OnEnable - 期望每个对象有独立状态——所有引用都指向同一资源。如果两个敌人需要不同的当前生命值,应将生命值存储在MonoBehaviour中,而非共享SO。
- 没有帧生命周期——ScriptableObject有/
OnEnable/OnDisable方法,但没有OnDestroy。不要期望每帧回调。Update - 将SO用作保存文件——它们是创作资源,而非运行时持久化工具;应使用来记录进度。
save-systems - 对象泄漏——运行时创建的实例不会像普通C#对象那样被垃圾回收;使用完毕后需调用
CreateInstance销毁它们。Destroy
References
参考资料
- For the event-channel pattern (a SO + listeners, type-safe payloads) and runtime sets/registries (a shared list of active enemies), read
GameEvent.references/event-channels.md - Primary docs: Unity Manual "ScriptableObject" () and
/Manual/class-ScriptableObject.html,ScriptReference/ScriptableObject.ScriptReference/CreateAssetMenuAttribute
- 关于事件通道模式(SO + 监听器、类型安全负载)和运行时集合/注册表(活动敌人的共享列表),请阅读
GameEvent。references/event-channels.md - 官方文档:Unity手册“ScriptableObject”()以及
/Manual/class-ScriptableObject.html、ScriptReference/ScriptableObject。ScriptReference/CreateAssetMenuAttribute
Related skills
相关技能
- — the MonoBehaviours that consume these assets.
unity-csharp-scripting - — persisting state to disk (what SOs are not for).
save-systems - /
card-game/rpg— genres that lean on SO-driven data.survival-crafting
- ——使用这些资源的MonoBehaviours。
unity-csharp-scripting - ——将状态持久化到磁盘(这不是SO的用途)。
save-systems - /
card-game/rpg——依赖SO驱动数据的游戏类型。survival-crafting