These are the docs for 13.4, an old version of SpatialOS. The docs for this version are frozen: we do not correct, update or republish them. 14.5 is the newest →

Handling data received from SpatialOS

All code examples in this section assume using Improbable.Worker; and using Example; (the generated code namespace).

Processing operations

It is up to you to decide how the basic event loop of receiving data from SpatialOS should be structured, depending on the worker’s requirements.

The worker needs to:

  1. Call Improbable.Worker.Connection.GetOpList to get a list of “operations” (for example entity creation, or a component update) that have been sent since the last time the function was called.
  2. Pass the Improbable.Worker.OpList to a Dispatcher, in order to invoke callbacks.

If you provide a positive timeout (in milliseconds) to GetOpList, the function will block until there is at least one operation to return, or until the timeout has been exceeded.

If the connection fails (when Connection.IsConnected() == false), any error messages explaining the cause will be returned by GetOpList(). Make sure to process this list in order to receive all available diagnostic information.

In order to detect that a worker is still responsive, SpatialOS sends periodic heartbeat requests. Responding to these happens automatically, but the buffer for incoming operations can fill up with other messages. If that happens, the heartbeats cannot be processed and your worker may be killed. Therefore, you should never wait multiple seconds between calls to GetOpList.

Example of processing operations

The following snippet shows a simple example implementation of an event loop that processes operations from SpatialOS 60 times per second:

const int FramesPerSecond = 60;

private static void RunEventLoop(Connection connection, Dispatcher dispatcher)
  var maxWait = System.TimeSpan.FromMilliseconds(1000f / FramesPerSecond);
  var stopwatch = new System.Diagnostics.Stopwatch();
  while (true)
    var opList = connection.GetOpList(0 /* non-blocking */);
    // Invoke callbacks.
    // Do other work here...
    var waitFor = maxWait.Subtract(stopwatch.Elapsed);
    System.Threading.Thread.Sleep(waitFor.Milliseconds > 0 ? waitFor : System.TimeSpan.Zero);

Dispatcher callbacks

To respond to operations, register callbacks on the Dispatcher. Each method takes an arbitrary callable System.Action<Param>, where the parameter type Param depends on the particular kind of callback being registered.

Timing and threading

You have complete control over callback timing and threading decisions. Dispatcher callbacks are invoked:

Caveats about receiving component updates

Note that the component updates:

  • can be partial, i.e. only update some properties of the component
  • do not necessarily have to contain data that is different from the worker’s current view of the component
  • could have been sent by SpatialOS rather than a worker for synchronization purposes

Registering callbacks

Here’s an example of registering callbacks:

private static System.Collections.Generic.List<ulong> RegisterCallbacks(Connection connection, Dispatcher dispatcher)
  var callbackKeys = new System.Collections.Generic.List<ulong>
    dispatcher.OnAddEntity(op =>
      // Do something with op.EntityId.
    dispatcher.OnComponentUpdate<Switch>(op =>
      var update = op.Update.Get();
      foreach (var toggleEvent in update.toggled)
        System.Console.WriteLine("Switch has been toggled at {0}.", toggleEvent.time);

  return callbackKeys;

Unregistering callbacks

To unregister a callback, call Remove() with the ulong returned from the registration method:

private static void UnregisterCallbacks(Dispatcher dispatcher, System.Collections.Generic.List<ulong> callbackKeys)
  foreach (var key in callbackKeys)

Dispatcher callbacks reference

Dispatcher callback Invoked when… Parameter type
OnDisconnect The Connection is no longer connected and can no longer be used.
Check the log for errors relating to the disconnection.
OnFlagUpdate A worker flag has been created or deleted, or its value has changed. FlagUpdateOp
OnLogMessage The SDK issues a log message for the worker to print. This does not include messages sent using Connection.SendLogMessage. LogMessageOp
OnMetrics The SDK reports built-in internal metrics. MetricsOp
OnCriticalSection A critical section is about to be entered or has just been left. CriticalSectionOp
OnAddEntity An entity is added to the worker’s view of the simulation. AddEntityOp
OnRemoveEntity An entity is removed from the worker’s view of the simulation. RemoveEntityOp
OnReserveEntityIdResponse The worker receives a response for an entity ID reservation it requested. ReserveEntityIdResponseOp
OnReserveEntityIdsResponse The worker has receives a response for the reservation of an entity ID range it requested. ReserveEntityIdsResponseOp
OnCreateEntityResponse The worker receives a response for an entity creation it requested. CreateEntityResponseOp
OnDeleteEntityResponse The worker receives a response for an entity deletion it requested. DeleteEntityResponseOp
OnEntityQueryResponse The worker receives a response for an entity query. EntityQueryResponseOp
OnAddComponent<C> A component is added to an entity in the worker’s view of the simulation. AddComponentOp<C>
OnRemoveComponent<C> A component is removed from an entity in the worker’s view of the simulation. RemoveComponentOp
OnAuthorityChange<C> The worker’s authority state over a component changes (to Authoritative, Not Authoritative or Authority Loss Imminent). AuthorityChangeOp
OnComponentUpdate<C> A component on an entity in the worker’s view of the simulation is updated. ComponentUpdateOp<C>
OnCommandRequest<C> The worker receives a command request for a component on an entity over which it has authority. CommandRequestOp<C>
OnCommandResponse<C> The worker receives a command response for a command request. CommandResponseOp<C>

Dispatcher invocation order

When processing an OpList, callbacks for most operations are invoked in the order they were registered with the Dispatcher. However, some operations naturally come in pairs of “start” and “end” operations, and the callbacks for the “end” operation are invoked in the reverse of the order they were registered.

This means that pairs of callbacks registered for the “start” and “end” operations can correctly depend on resources managed by pairs of callbacks registered previously, similar to the usual construction and destruction order found in e.g. C++.

For example:

  • AddEntityOp and AddComponentOp callbacks are invoked in the order they were registered with the Dispatcher. RemoveEntityOp and RemoveComponentOp callbacks are invoked in reverse order.
  • AuthorityChangeOp callbacks are invoked in the order they were registered when authority is granted, but in reverse order when authority is revoked (or authority loss is imminent).
  • CriticalSectionOp callbacks are invoked in usual order when a critical section is entered but reverse order when a critical section is left.
  • FlagUpdateOp callbacks are invoked in the order they were registered when a worker flag is created or its value is changed, but in reverse order when a worker flag is deleted.

In particular, this invocation order has the side-effect that the final state of a component removed in a RemoveComponentOp callback can still be inspected in the View.

Using the View

Improbable.Worker.View is a subclass of Improbable.Worker.Dispatcher, which automatically maintains the current state of the worker’s view of the simulated world.

It has a field called Entities, which is a map from entity ID to Improbable.Worker.Entity objects. When a View processes an OpList, it automatically updates the state of this map as appropriate. Any user-defined callbacks are also invoked, as per the Dispatcher contract.

Critical sections

The protocol supports the concept of critical sections. A critical section is a block of operations that should be processed atomically by the worker. For example, a set of entities representing a stack of cubes should be added to the scene in its entirety before any physics simulation is done.

This notion of a critical section does not provide any guarantees.

The CriticalSectionOp callback is invoked with InCriticalSection == true just before the first operation of the critical section is delivered, and is invoked again with InCriticalSection == false just after the last operation of the critical section is delivered.

Worker flags

To access the value of a worker flag, use the Connection.GetWorkerFlag() method:

const double DefaultWorkSpeed = 10;

private static void GetSpeedWorkerFlag(Connection connection)
  var speedFlag = connection.GetWorkerFlag("mycompany_theproject_speed");
  if (speedFlag.HasValue)

Worker flags are updated before the registered callbacks are invoked, so it is recommended to store the worker flag values in user code when using callbacks and only use GetWorkerFlag for checking the initial flag values.

Search results

Was this page helpful?

Thanks for letting us know!

Thanks for your feedback

Need more help? Ask on the forums