Skip to content
EN

脚本组件 ​

suity.script 是唯一的脚本组件类型,只有 *.component.ts(资产类型 scriptComponent)可以被挂载。普通 .ts 文件只能作为依赖参与打包,不能直接挂到节点上。

最小脚本 ​

ts
import { ScriptComponent } from "@suity/engine-pixi/script";

export default class PlayerController extends ScriptComponent {
  private speed = 180;

  onStart() {
    this.log("player ready", this.node.name);
  }

  onUpdate(dt: number) {
    const dir = this.input.axis("MoveX");
    const body = this.node.container();
    body.x += dir * this.speed * dt;

    if (this.input.pressed("Jump")) {
      this.warn("jump is handled by platformer2d in game projects");
    }
  }

  onDestroy() {
    this.log("player destroyed");
  }
}

脚本通过 default export 暴露类;构建时会为每个脚本生成稳定的 runtimeKey 与 manifest 条目,manifest 声明 sdkVersion: "1.0.0"。

生命周期 ​

回调时机说明
onStart()挂载完成对应统一 Handler 的 onLoad
onEnable()组件/节点变为启用可选
onUpdate(dt)每帧dt 单位为秒
onDisable()组件/节点失活可选
onDestroy()停止或卸载释放监听与外部资源

ScriptComponent 内部实现了统一的 ComponentHandler 生命周期,因此脚本与模块组件共享 enabled / active 语义。

可用的上下文 ​

成员类型用途
this.nodeNode所属节点:查询子节点、解析 resolve(path)、读写组件
this.sceneScene场景级查询、结构修改、mainCamera、signals
this.inputInputStateaxis / held / pressed / released
this.assetsScriptAssetsresolve / load 资产
this.signalsScriptSignals节点信号读写、监听与 provider 注册
this.componentComponentHandle当前 suity.script 组件句柄
this.componentRefstring当前挂载的稳定 componentRef

日志请使用 this.log() / this.warn() / this.error(),它们会进入 Play 的 Output 面板,而不是直接写 console。

挂载与构建 ​

  • 在编辑器中通过「添加组件 → Script」挂载 *.component.ts,持久化为 { script: <asset uid> }。
  • Play 中动态挂载的脚本写 { runtimeScript, runtimeScriptName },没有资产 UID,不进入场景文档、dirty 与 undo,Stop 后销毁。
  • 构建默认打包全部 .component.ts,支持动态 class 注册;宿主不内置 TypeScript 编译器,脚本构建由项目的 build:scripts 完成。

与模块组件的关系 ​

模块(Actor、Platformer 2D 等)的组件 handler 与 ScriptComponent 共用同一套 ComponentHandler 生命周期和 SDK Node / Scene / ComponentHandle。区别只在于:

  • 模块组件由模块 manifest 的 sdkApiVersion 声明兼容性;
  • 脚本由场景文档或运行时动态挂载;
  • 同节点可以挂多个脚本,每个挂载拥有独立的 componentRef。

详见 Script API。

Suity 开发者文档 · API 由 TypeDoc 从声明文件生成