| name | vtj-scene-management |
| description | Orchestrates World lifecycle and component initialization. Use when managing initialization order, update sequences, or implementing proper disposal chains. |
vite-threejs Scene Management
Overview
World 类作为场景 orchestrator,管理所有 3D 组件的生命周期。核心原则:等待资源、顺序注册、顺序更新、逆序清理。
When to Use
- 创建新的 World 或主场景管理器
- 添加新的 3D 组件到场景
- 管理组件初始化顺序
- 确保资源正确清理
Core Patterns
1. 等待资源 (Wait for Resources)
所有依赖资源的组件在 core:ready 后初始化:
constructor() {
this.experience = new Experience()
emitter.on('core:ready', () => {
this.initComponents()
})
}
2. 顺序注册 (Registration Order)
示例: 按依赖关系顺序创建组件:
initComponents() {
this.chunkManager = new ChunkManager()
this.player = new Player()
this.cameraRig = new CameraRig()
this.cameraRig.attachPlayer(this.player)
this.environment = new Environment()
this.blockRaycaster = new BlockRaycaster({
chunkManager: this.chunkManager
})
}
3. 顺序更新 (Update Order)
update() 中按依赖顺序调用:
update() {
this.chunkManager?.updateStreaming()
this.chunkManager?.update()
this.player?.update()
this.environment?.update()
this.blockRaycaster?.update()
}
4. 逆序清理 (Reverse Disposal)
destroy() 中按相反顺序清理:
destroy() {
this.blockRaycaster?.destroy()
this.environment?.destroy()
this.cameraRig?.destroy()
this.player?.destroy()
this.chunkManager?.destroy()
}
Quick Reference
| 阶段 | 原则 | 代码位置 |
|---|
| 初始化 | 等待 core:ready | emitter.on('core:ready', ...) |
| 注册 | 依赖先行 | constructor 或 init 方法 |
| 更新 | 数据流顺序 | update() 方法 |
| 清理 | 逆序销毁 | destroy() 方法 |
Common Mistakes
❌ 在 core:ready 之前访问资源
constructor() {
this.model = this.resources.items['playerModel']
}
emitter.on('core:ready', () => {
this.model = this.resources.items['playerModel']
})
❌ 忘记更新子组件
update() {
this.player.update()
}
update() {
this.chunkManager?.update()
this.player?.update()
}
❌ 清理顺序错误
destroy() {
this.chunkManager?.destroy()
this.player?.destroy()
}
destroy() {
this.player?.destroy()
this.chunkManager?.destroy()
}