How to make simple chat system using Fish-Networking


In this post, I will show you how to make a simple chat system using Fish-Networking.

A video explaining this post in detail is available on my channel.

So, to make it so all objects regardless of whether they're NetworkBehaviours or not can send messages, we will be utilizing a powerful feature of Fish-Networking called Broadcasts.

Broadcasts allow clients to send messages to the server and vice versa. They can be created by defining a struct (or preferably a read-only struct) and implementing the IBroadcast interface.

With that said, let's create a broadcast called SendMessageBroadcast like so:

public readonly struct SendMessageBroadcast : IBroadcast
    public readonly string Sender;
    public readonly string Message;
    public SendMessageBroadcast(string sender, string message)
        Sender = sender;
        Message = message;

As you can see, our broadcast is pretty simple. It has 2 properties, Sender and Message.

Now, let's go ahead and create a Chat component that will be responsible for handling incoming messages.

public sealed class Chat : NetworkBehaviour
    public readonly SyncList<string> Messages = new SyncList<string>();
    public override void OnStartServer()
    public override void OnStopServer()
    private void SendMessageBroadcastHandler(NetworkConnection networkConnection, SendMessageBroadcast broadcast)
        Messages.Add($"{broadcast.Sender}: {broadcast.Message}");

As you can see, our Chat component derives from NetworkBehaviour, overrides the OnStartServer, and OnStopServer methods. Inside them, we're registering and unregistering a server handler for the SendMessageBroadcast broadcast so that when a client sends a message, we can add it to our Messages sync list.

Now, to send a message, call ClientManager.Broadcast with the SendMessageBroadcast from anywhere like so:

InstanceFinder.ClientManager.Broadcast(new SendMessageBroadcast("Me", "Hello!"));

And, that's it!

Messages sent by clients will be added to our Messages sync list and be accessible by any client connected to the server.

Enjoy this post?

If you found this content helpful, consider sharing it with others, or if you'd like to support my work directly, you can buy me a coffee on Ko-fi.

Your support helps me create more awesome content. Thank you!