Get SpatialOS

Sites

Menu

How to send and receive events

This document relates to the MonoBehaviour workflow.

Events are SpatialOS’s equivalent of broadcasted messages. They allow you to send messages to all interested workers.

For more information, see the documentation on events.

We provide code-generated Readers and Writers for sending and receiving SpatialOS events. Before reading this document, make sure you are familiar with

We use the following schema for all examples described in this documentation.

package playground;

type Location
{
  float x = 1;
  float y = 2;
  float z = 3;
}

component Bomb
{
	id = 12002;
	event Location explode;
}

This will generate the following classes in the Playground namespace:

  • Bomb.Requirable.Reader
  • Bomb.Requirable.Writer

How to send events

The following code snippet provides an example on how to send events. To send an event, ensure that your worker has write authority over the corresponding SpatialOS component.

using Playground;

public class TriggerExplosion : MonoBehaviour
{
	[Require] private Bomb.Requirable.Writer bombWriter;

	private void Update()
	{
    	if (Input.GetKeyDown(KeyCode.Space))
    	{
        	bombWriter.SendExplode(new Location(1, 1, 1));
    	}
	}
}

How to receive events

The following code snippet provides an example on how to receive events. Any worker that has your entity checked out and has read access over the corresponding SpatialOS component can receive events.

using Playground;

public class HandleExplosion : MonoBehaviour
{
	[Require] private Bomb.Requirable.Reader bombReader;

	private void OnEnable()
	{
    	bombReader.OnExplode += OnExplode;
	}

	private void OnDisable()
	{
    	// all registered callbacks are automatically deregistered when this script is disabled.
    	// Do not deregister your callback as it is an invalid operation.
	}

	private void OnExplode(Location location)
	{
    	// show the explosion
	}
}

Search results

Was this page helpful?

Thanks for letting us know!

Thanks for your feedback

Need more help? Ask on the forums