Skip to content
Pedro Clerici edited this page Jul 26, 2025 · 1 revision

Events allow you to run logic in response to something that happened in your game, and can be used as a means of cross-system communication. Events are instances of classes and live in a queue of other events of the same type. New events can be pushed to the queue with EventWriter<T>, and events in the queue can be read with EventReader<T>.

Events have no set lifetime - they will persist until the queue is manually cleared. Writers can call the clear() method to remove all events from the current queue, or you can add the clearAllEventQueues system to your schedule!

EventReader

EventReaders are responsible for reading data from the event queue.

They can be iterated over in a for...of loop, and will yield instances of the event type. You can also check their length to determine the number of elements in the queue.

class LevelUpEvent {
	level: number = 0;
}

export function readLevelUpEvents(
	levelUpEvents: EventReader<LevelUpEvent>,
	audio: Res<Audio>,
) {
	if (levelUpEvents.length === 0) {
		return;
	}
	for (const luEvent of levelUpEvents) {
		if (luEvent.level % 10 === 0) {
			audio.playSuperCoolSound();
		} else {
			audio.playLessCoolSound();
		}
	}

	levelUpEvents.clear();
}

EventWriter

EventWriter inherits all functionality of EventReader, and is also responsible for adding events to the queue. You can add events to the queue with create(value: T): void, which simply pushes the provided value to the queue. The passed value must be an instance of the class.

EventWriters can also call clearImmediate() to immediately remove all events from the queue.

class LevelUpEvent {
	level: number = 0;
}

export function writeLevelUpEvents(levelUpEvents: EventWriter<LevelUpEvent>) {
	levelUpEvents.createDefault();
	console.log(levelUpEvents.length); // -> 1

	// A clear command has been queued, but events still exist.
	levelUpEvents.clear();
	console.log(levelUpEvents.length); // -> 1

	// Now we're removing events immediately.
	levelUpEvents.clearImmediate();
	console.log(levelUpEvents.length); // -> 0
}

Clone this wiki locally