Should I fire an event on the script component or the entity?

Say I have a script component that fires an event. Should I fire the event on the script component or the entity? Which is the standard approach in PlayCanvas?

Script component fires an event:

this.fire('load');

Users adds an event handler on the script component:

const scriptComponent = entity.script.create('myScriptComponent');
scriptComponent.once('load', function() {}, this);

Script component fires event on the entity:

this.entity.fire('my-script-component-load');

User adds an event handler on the entity:

entity.on('my-script-component-load', function() {}, this);

There’s no standard approach. It depends on the pattern you want use/build in your game.

I personally prefer firing on the entity for broadcasting events to other script types on the same entity as a ‘shared inbox’ pattern.

It means that each script type on the entity doesn’t need to actually be aware or know about other script types on the entity and keeps things neater IMO

1 Like