9.1 原型-实例嵌套
场景里布满重复结构:十个长得一样的敌人、一百个相同的子弹。工业级编辑器的答案不是「复制粘贴十遍」,而是原型——一份可复制的定义,加上它在场景里的实例。
PrototypeRegistry 注册原型:名字 + 字段 + 可选的嵌套子结构。createInstance(name, id) 把原型实例化到场景:深拷贝字段、递归实例化子结构。三条性质是这个设计的全部:
- 改实例不影响原型:
enemy的字段是模板,实例e1把hp改成 50,原型还是 100。 - 实例之间互不影响:
e1改speed,e2纹丝不动。 - 嵌套递归成立:
enemy的子结构body/head本身也是原型,实例化时递归展开。
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 对象图 | 8.3 对象图引用 | 引用图管跨对象指向;原型管复用定义 |
| 覆盖继承 | 9.2 变体覆盖继承 | 本节是纯复制;下节升级为「模板 + 覆盖表」 |
| Prefab 更新 | 9.3 Prefab 更新迁移 | 模板演进后既有实例怎么迁移 |
| 资产 GUID | 卷三 8.4 资产 GUID | 原型名是稳定标识;GUID 用于资产引用 |
深拷贝:为什么必须 structuredClone
createInstance 用 structuredClone 复制字段,而不是 {...fields} 浅拷贝。理由藏在嵌套对象里:transform: { pos: [1, 2, 3] } 浅拷贝会让两个实例共享同一个 transform 对象——e1 改 pos[0],e2 的位置跟着变。这是经典的「看起来独立、其实共享」的 bug,症状最难排查。深拷贝保证实例的嵌套结构也真正独立。
代价是拷贝成本:原型越大、实例越多,structuredClone 越贵。这就是为什么工业级编辑器会区分「运行时创建用实例克隆」和「编辑态用模板 + 覆盖」(9.2)——纯复制是简单可靠的语义,覆盖表是省内存的高阶语义,按场景选。
对标模板实例与运行时副本
Unity Prefab 和 Cocos Creator Prefab 都可在编辑器中创建关联模板的实例。Godot 的场景实例也可复用源场景并保留局部属性值。Unreal 的 Level Instance 可复用一组场景 Actor,Blueprint 则复用类及其行为。Cocos Creator 3.8 Prefab · Godot 场景实例 · Unreal Level Instancing
helio 本节仅实现模板复制。下一节引入覆盖表,保存实例相对于模板的局部修改。
可运行产物:6 条用例
下面 src/prototype-instance.ts 层级 L1,完整可编译,命令 node --test test/09-1-prototype-instance-nesting.test.ts:
// file: src/prototype-instance.ts
// tier: L1
// verify: node --test test/09-1-prototype-instance-nesting.test.ts
//
// 对象图、Prefab 与 Preset(第九章):原型-实例嵌套。
// 原型是一份「可复制的定义」,实例是它在场景里的化身。PrototypeRegistry
// 注册原型(字段 + 可选的嵌套子结构),createInstance 深拷贝字段并递归
// 实例化子结构——改实例不影响原型,两个实例互不影响。这是 Prefab
// (Unreal/Unity)和预设(Preset)共同的地基:没有原型就没有实例。
export interface PrototypeDef {
name: string;
fields: Record<string, unknown>;
/** 嵌套子原型结构:path 是实例里的位置,name 指向另一个原型。 */
children?: { path: string; name: string }[];
}
export interface InstanceNode {
id: string;
/** 实例所属原型名;null 表示原生节点。 */
proto: string | null;
fields: Record<string, unknown>;
children: InstanceNode[];
}
export class PrototypeRegistry {
readonly #defs = new Map<string, PrototypeDef>();
register(def: PrototypeDef): boolean {
if (this.#defs.has(def.name)) return false;
this.#defs.set(def.name, def);
return true;
}
prototype(name: string): PrototypeDef | undefined { return this.#defs.get(name); }
has(name: string): boolean { return this.#defs.has(name); }
/** 深拷贝原型字段并递归实例化子结构;未注册原型返回 undefined。 */
createInstance(name: string, id: string): InstanceNode | undefined {
const def = this.#defs.get(name);
if (!def) return undefined;
const children = (def.children ?? []).map((c) => {
const child = this.createInstance(c.name, `${id}/${c.path}`);
return child ?? { id: `${id}/${c.path}`, proto: c.name, fields: {}, children: [] };
});
return { id, proto: name, fields: structuredClone(def.fields), children };
}
}
递归是嵌套的关键:children.map 里调用 createInstance(c.name, ...),每个子结构都是一次独立的原型实例化——子实例自己的 children 又会递归展开,任意深度的嵌套都成立。proto 字段记录「我是谁的实例」,这是 9.2 覆盖表、9.3 更新迁移的锚点:没有它,编辑器无法知道一个实例该向哪个模板对齐。
可运行产物:6 条用例
下面是 test/09-1-prototype-instance-nesting.test.ts 层级 L1,命令 node --test test/09-1-prototype-instance-nesting.test.ts:
// file: test/09-1-prototype-instance-nesting.test.ts
// tier: L1
// verify: node --test test/09-1-prototype-instance-nesting.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { PrototypeRegistry } from '../src/prototype-instance.ts';
const enemyDef = {
name: 'enemy',
fields: { hp: 100, speed: 3 },
children: [
{ path: 'body', name: 'enemy-body' },
{ path: 'head', name: 'enemy-head' },
],
};
function registry(): PrototypeRegistry {
const r = new PrototypeRegistry();
r.register({ name: 'enemy-body', fields: { mesh: 'body.glb' } });
r.register({ name: 'enemy-head', fields: { mesh: 'head.glb' } });
r.register(enemyDef);
return r;
}
test('createInstance 深拷贝字段,改实例不影响原型', () => {
const r = registry();
const inst = r.createInstance('enemy', 'e1')!;
assert.equal(inst.proto, 'enemy');
assert.equal(inst.fields.hp, 100);
inst.fields.hp = 50; // 改实例
assert.equal(r.prototype('enemy')!.fields.hp, 100); // 原型不受影响
});
test('相同原型两次实例化互不影响', () => {
const r = registry();
const a = r.createInstance('enemy', 'e1')!;
const b = r.createInstance('enemy', 'e2')!;
a.fields.speed = 10;
assert.equal(b.fields.speed, 3);
});
test('嵌套子结构按原型递归实例化', () => {
const r = registry();
const inst = r.createInstance('enemy', 'e1')!;
assert.equal(inst.children.length, 2);
const body = inst.children.find((c) => c.id === 'e1/body')!;
assert.equal(body.proto, 'enemy-body');
assert.equal(body.fields.mesh, 'body.glb');
});
test('未注册原型 createInstance 返回 undefined', () => {
const r = registry();
assert.equal(r.createInstance('ghost', 'x'), undefined);
});
test('注册重复原型名被拒绝', () => {
const r = new PrototypeRegistry();
r.register(enemyDef);
assert.equal(r.register(enemyDef), false);
});
test('嵌套对象字段深拷贝(不共享引用)', () => {
const r = new PrototypeRegistry();
r.register({ name: 'crate', fields: { transform: { pos: [1, 2, 3] } } });
const a = r.createInstance('crate', 'c1')!;
const b = r.createInstance('crate', 'c2')!;
a.fields.transform.pos[0] = 99;
assert.deepEqual(b.fields.transform.pos, [1, 2, 3]);
});
本机实测(Node v26.5.0,node --test test/09-1-prototype-instance-nesting.test.ts):tests 6、pass 6、fail 0,耗时约 40 ms。
第一条把「实例改原型不动」钉死;第二条把「实例之间互不影响」钉死;第三条验证嵌套递归——e1/body 的 proto 是 enemy-body、mesh 字段正确。第六条专攻浅拷贝陷阱:a.fields.transform.pos[0] = 99 后 b 的 pos 仍是 [1,2,3]——structuredClone 的深拷贝语义在此接受检验。
小结
- 原型 = 可复制的定义,实例 = 场景里的化身;
createInstance深拷贝字段、递归实例化子结构。 - 三条性质:改实例不改原型、实例互不影响、任意深度嵌套成立。
structuredClone深拷贝防止「看着独立、实则共享」的嵌套对象陷阱。- 对标 Unity Prefab / Godot PackedScene:helio 先纯复制(简单正确),下节在纯复制之上加覆盖表获得模板联动。
- 下一节把纯复制升级为「模板 + 覆盖」:变体覆盖继承——OverrideTable 记录差异,覆盖优先合成可见值。
阅读导航:上一节:8.3 对象图引用 · 下一节:9.2 变体覆盖继承 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。