Events and EventBus
The sender announces a change, and subscribers decide how to respond.
EventBus connects services, components, and the FSM through events. When the score changes, the service sends ScoreChanged. The text node can respond on its own.
The service sends the event as shown below. BlockPuzzleGameplayService.ts
this.sceneContext.engine.events.emit({
type: BlockPuzzleEvents.ScoreChanged,
data: { score: this.getSession().score, delta },
});
The public emit method takes data. The subscriber receives an AppEvent with the same data in payload. Here is a shortened handler. BlockPuzzleScoreComponent.ts
const off = this.node.events.on(BlockPuzzleEvents.ScoreChanged, (event) => {
const payload = SchemaDecoder.decode(
event.payload,
BlockPuzzleEventSchemas.ScoreChanged,
BlockPuzzleEvents.ScoreChanged,
);
this.node.setText(String(payload.score));
});
The example combines subscribing and updating the text. The original component puts them in separate methods. Save the off function and call it when disabling the component.
on subscribes to one event type, and onAny subscribes to all events. Both return a function that unsubscribes.
emit continues while asynchronous handlers finish. Use FSM commands when execution order matters.