Broadcasts
Last updated
Last updated
Broadcasts allow you to send messages to one or more objects without them requiring a NetworkObject component. This could be useful for communicating between objects which are not necessarily networked, such as a chat system.
Like , broadcasts may be sent reliably or unreliably. Data using broadcasts can be sent from either from the client to the server, or server to client(s). Serializers are automatically generated for Broadcasts as well.
Broadcasts must be structures, and implement IBroadcast. Below demonstrates what values a chat broadcast may possibly contain.
Since broadcasts are not linked to objects, they must be sent using the , or . When sending to the server you will send using ClientManager, and when sending to clients, use ServerManager.
The following examples use the InstanceFinder to get a reference to the ClientManager and ServerManager, but you can store a reference yourself, use the NetworkManager's public references or a NetworkBehaviour's.
Here is an example of sending a chat message from a client to the server.
Given broadcasts are not automatically received on the object they are sent from you must specify what scripts, or objects can receive a broadcast. As mentioned previously, this allows you to receive broadcast on non-networked objects, but also enables you to receive the same broadcast on multiple objects.
While our example only utilizes one object, this feature could be useful for changing a large number of conditions in your game at once, such as turning off or on lights without having to make them each a networked object.
Listening for a broadcast is much like using events. Below demonstrates how the client will listen for data from the server.
As a reminder, a receiving method on the server was demonstrated above. The method signature looked like this.
With that in mind, let's see how the server can listen for broadcasts from clients.
If you would like to view a working example of using Broadcast view the PasswordAuthentictor.cs file within the Demos/Authenticator/Scripts
folder.
Sending from the server to client(s) is done very much the same, but you are presented with more options. For a complete list of options I encourage you to view the . Here is an example of sending a broadcast to all clients which have visibility of a specific client. This establishes the idea that clientA sends a chat message to the server, and the server relays it to other clients which can see clientA. In this example clientA would also get the broadcast.