Show Sidebar

In Depth - Protocol Tokens

Bolt sports a feature called Protocol Tokens, they are used to attach arbitrary data (C# objects) to specific actions that can be taken in Bolt, a few examples:

  • Instantiating an entity
  • Connecting to a server
  • Loading a scene

The reason for Protocol Tokens existing is that in a lot of cases you want some small piece of data available when a specific action happens. Due to the unreliable nature of networking for the data to be guaranteed to be there it has to be sent with the action itself. Protocol Tokens allows you to accomplish this.

A few examples of data you might want to be available when a specific action happens are:

  • When instantiating a players character you want to send the customization options for that the player has selected.
  • You want players to send a username and password when connecting to a server.
  • When loading a new scene you want the season (fall, winter, etc.) to be available when the scene starts loading so you can load the correct textures, etc.

Protocol Tokens are created by simply defining a normal C# class and inherit from the Bolt.IProtocolToken interface. This interface defines two methods: Write and Read. They also need to be implemented in your class.

Here we define a protocol token which will contain some character customization data for when we instantiate an entity. It contains two simple integer fields which represent id numbers of the skin and hat of our pretend character.

In the Write method we write the data into the packet by calling the appropriate WriteXXX() method on the packet object passed in. We do the reverse in Read and call the proper ReadXXX() method on the packet passed in.

Important: You have to call the same corresponding WriteXXX and ReadXXX methods on the packet in the same order in the Write and Read methods.

To use our Protocol Token class we have to register it with Bolt, this should be done in the BoltStarted callback which you can implement by creating a Unity behaviour which inherits from Bolt.GlobalEventListener, more details about how Bolt.GlobalEventListener works can be found in the In Depth - Global Callbacks section.

Registering a token class is done by calling BoltNetwork.RegisterTokenClass<T>() and passing in the class as the generic parameter T, see below for an example.

Now when we call BoltNetwork.Instantiate method we can pass in an instance of our CharacterCustomization class:

We can then access this token in the Attached callback on our C# scripts that inherit from Bolt.EntityBehaviour and Bolt.EntityBehaviour<T> like this:

 To Document Top