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
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.
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
ReadXXX methods on the packet in the same order in the
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
More details about how
Bolt.GlobalEventListener works can be found in the "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
We can then access this token in the
Attached callback on our C# scripts that inherit from
Bolt.EntityBehaviour<T> like this: