Events

IntermediateProgrammer

Events facilitate communication between scripts. They work one-way, broadcast from broadcasters to receivers.

For example, imagine your game has a "Game Over" state that occurs when the player dies. To handle this, you can create a "Game Over" event, which is broadcast to all scripts with receivers listening for the event. When the event is broadcast, the receivers run appropriate scripts to handle the Game Over event (eg reset enemies, replace level objects, start a new timer, etc).

Note

Events are handled entirely in scripts. You can't configure them in Game Studio.

Create and broadcast an event

Broadcasters in the Xenko API are of type EventKey. They use the method Broadcast to broadcast events to receivers.

For example, this code creates a "Game Over" event:

  1. public static class GlobalEvents
  2. {
  3. public static EventKey GameOverEventKey = new EventKey("Global", "Game Over");
  4. public static void SendGameOverEvent()
  5. {
  6. GameOverEventKey.Broadcast();
  7. }
  8. }

Create a receiver

Receivers in the Xenko API are of type EventReceiver.

To receive the "Game Over" event described above, use:

  1. var gameOverListener = new EventReceiver(GlobalEvents.GameOverEventKey);
  2. var gameIsOver = gameOverListener.TryReceive();
  3. //Or in Async
  4. await gameOverListener.ReceiveAsync();

See also