Skip to content
On this page

Messages

In a running game it's useful to be able to notify other components and entities that something happend. Instead of iterating over entities and components by hand you can use the integrated message system.

Especially when dealing with large amounts of objects the message system helps to propagate data to other objects in a fast and predictable fashion.

Scope

A message is composed of a name with an optional payload that is sent within a certain scope. Depending on the information you can decide for whom the message might be important and select a scope accordningly.

Function Call in ComponentTarget
this.sendMessageToEntityReaches only Components of this Entity
this.sendMessageToActive or this.world.sendMessage(msg, props, true)Reaches only active Entities in the given world
this.sendMessageToAll or this.world.sendMessage(msg, props, false)Reaches all Entities in the given world
this.world.manager.sendMessageToAllWorldsAll Entities in all populated worlds

World

Send a message

ts
// in a component

this.sendMessageToEntity("UseSword", {power: 23})
this.sendMessageToActive("UseSword", {power: 23})
this.sendMessageToAll("UseSword", {power: 23})   
this.world.manager.sendMessageToAllWorlds("UseSword", {power: 23}) 
this.world.manager.getWorldByName("UI").sendMessage("UseSword", {power: 23})

Receive a message

ts
export class MyComponent extends Component {
    
    private onMessage_UseSword({power}) {
    }

    private onMessage_EnemyScreams(props) {
    }
}

There is no registration or addListener() required. If the function name matches the pattern: onMessage_<messageName> and if the Component is in a matching scope it'll receive the message.

TIP

In Typescript it is safe to use private functions here. The keyword is just sugar and Javascript ignores that.

Performance

Javascript handles dynamic function calls pretty well. However, in generel it's suggested to send messages only when specific events happen. Big events like: GameOver, PlayerEntersWater or an UI event like ButtonPressed.

Picking the right scope also helps to minimize the CPU load. Sending a message to the current Entity is way quicker than sending it to all worlds.