🐾PurrNet Docs
Advanced

Broadcasts

Broadcasts send arbitrary data packets over a connection without requiring a NetworkIdentity. They are ideal for lobby data, global chat, and any messages that exist before or outside of spawned objects.

ObserversRpc (via NetworkIdentity)
Broadcast (connection-level)
ServerNetworkIdentityClient AClient B2 hops: Server → Object → ClientsManagerClient AClient B1 hop: Manager → Connections directly
RPC (ObserversRpc)
  • Requires a NetworkIdentity on the object
  • Only observers of that object receive it
  • Cannot be sent before spawn
Broadcast
  • No NetworkIdentity required
  • Sent on the connection channel directly
  • Works before any object is spawned

What makes broadcasts different

Every RPC in PurrNet is dispatched through a NetworkIdentity — the packet addresses a specific object on the network. Broadcasts are connection-scoped: they are addressed to a connection or to all connections, with no object in the middle.

This makes broadcasts the right tool when:

  • You need to communicate before any objects are spawned (lobby, authentication handshake)
  • The message is truly global and not owned by any game object (global chat, server announcements)
  • You are implementing a system that manages objects and should not itself be an object (a matchmaking service)

API reference

ParameterTypeDefaultDescription
BroadcastAll<T>(T data)void—Sends the data packet to every connected client. Called from the server.
BroadcastConnection<T>(NetworkConnection conn, T data)void—Sends the data packet to a single specific connection. Useful for private messages or targeted state.
BroadcastServer<T>(T data)void—Sends the data packet from a client up to the server. The server receives it via its registered handler.
Subscribe<T>(Action<T, NetworkConnection> handler)void—Registers a handler for broadcast packets of type T. The second parameter is the sender's connection (available on the server).
Unsubscribe<T>(Action<T, NetworkConnection> handler)void—Removes a previously registered handler. Always unsubscribe when done to prevent memory leaks.

Registering broadcast types

Any struct decorated with [System.Serializable] and implementing IPackedAuto (or a registered custom serializer) can be used as a broadcast payload. No additional registration is needed beyond what PurrNet requires for any serializable type.

Basic usage — server to all clients

ServerAnnouncement.cs
using PurrNet;
using UnityEngine;

[System.Serializable]
public struct ServerAnnouncementMsg : IPackedAuto
{
    public string text;
    public float  displayDuration;
}

public class AnnouncementSystem : MonoBehaviour
{
    private NetworkManager _nm;

    private void Awake()
    {
        _nm = GetComponent<NetworkManager>();
    }

    private void OnEnable()
    {
        // Subscribe on all machines
        _nm.Subscribe<ServerAnnouncementMsg>(OnAnnouncementReceived);
    }

    private void OnDisable()
    {
        _nm.Unsubscribe<ServerAnnouncementMsg>(OnAnnouncementReceived);
    }

    // Server calls this to push an announcement to everyone
    public void SendGlobalAnnouncement(string text, float duration = 5f)
    {
        if (!_nm.isServer) return;

        _nm.BroadcastAll(new ServerAnnouncementMsg
        {
            text            = text,
            displayDuration = duration,
        });
    }

    private void OnAnnouncementReceived(ServerAnnouncementMsg msg, NetworkConnection sender)
    {
        // Runs on every client when the server broadcasts
        AnnouncerUI.Show(msg.text, msg.displayDuration);
    }
}

Client → server broadcasts

Clients can also send data up to the server using BroadcastServer<T>. This is the broadcast equivalent of a [ServerRpc] — useful before any objects exist that could host an RPC.

LobbyChat.cs
using PurrNet;
using UnityEngine;

[System.Serializable]
public struct ChatMessage : IPackedAuto
{
    public string senderName;
    public string text;
    public float  timestamp;
}

public class LobbyChat : MonoBehaviour
{
    private NetworkManager _nm;

    private void Awake()
    {
        _nm = GetComponent<NetworkManager>();
    }

    private void OnEnable()
    {
        // Server listens for incoming chat messages from clients
        if (_nm.isServer)
            _nm.Subscribe<ChatMessage>(OnChatMessageFromClient);

        // All machines (including server) listen for the relayed broadcast
        _nm.Subscribe<ChatMessage>(OnChatMessageBroadcast);
    }

    private void OnDisable()
    {
        if (_nm.isServer)
            _nm.Unsubscribe<ChatMessage>(OnChatMessageFromClient);

        _nm.Unsubscribe<ChatMessage>(OnChatMessageBroadcast);
    }

    // Called by the local player when they press Send
    public void SendChatMessage(string text)
    {
        // No NetworkIdentity needed — just broadcast to the server
        _nm.BroadcastServer(new ChatMessage
        {
            senderName = PlayerPrefs.GetString("PlayerName", "Unknown"),
            text       = text,
            timestamp  = Time.time,
        });
    }

    // Server receives the client's chat and relays to all clients
    private void OnChatMessageFromClient(ChatMessage msg, NetworkConnection sender)
    {
        if (!_nm.isServer) return;

        // Optionally validate/moderate msg.text here
        _nm.BroadcastAll(msg); // relay to everyone
    }

    // Every client (and the server) displays the relayed message
    private void OnChatMessageBroadcast(ChatMessage msg, NetworkConnection sender)
    {
        LobbyChatUI.AddMessage(msg.senderName, msg.text);
    }
}

Situational example — pre-spawn matchmaking data

This example shows how a client can send matchmaking preferences to the server before any game objects are spawned, and how the server can reply with the assigned team — all via broadcasts.

MatchmakingBroadcasts.cs
using PurrNet;
using UnityEngine;

[System.Serializable]
public struct MatchmakingRequest : IPackedAuto
{
    public int    preferredTeam; // 0 = any, 1 = red, 2 = blue
    public string selectedSkin;
}

[System.Serializable]
public struct MatchmakingResponse : IPackedAuto
{
    public int    assignedTeam;
    public int    spawnPointIndex;
    public bool   accepted;
}

public class MatchmakingHandler : MonoBehaviour
{
    private NetworkManager _nm;

    private void Awake()
    {
        _nm = GetComponent<NetworkManager>();
    }

    private void OnEnable()
    {
        if (_nm.isServer)
            _nm.Subscribe<MatchmakingRequest>(OnClientRequest);
        else
            _nm.Subscribe<MatchmakingResponse>(OnServerResponse);
    }

    private void OnDisable()
    {
        if (_nm.isServer)
            _nm.Unsubscribe<MatchmakingRequest>(OnClientRequest);
        else
            _nm.Unsubscribe<MatchmakingResponse>(OnServerResponse);
    }

    // Client sends preferences when it connects
    public void RequestMatch(int preferredTeam, string skin)
    {
        _nm.BroadcastServer(new MatchmakingRequest
        {
            preferredTeam = preferredTeam,
            selectedSkin  = skin,
        });
    }

    // Server assigns and responds to the specific client
    private void OnClientRequest(MatchmakingRequest req, NetworkConnection sender)
    {
        int team  = TeamBalancer.AssignTeam(req.preferredTeam);
        int spawn = SpawnManager.ReservePoint(team);

        _nm.BroadcastConnection(sender, new MatchmakingResponse
        {
            assignedTeam    = team,
            spawnPointIndex = spawn,
            accepted        = true,
        });
    }

    // Client receives its assignment and prepares to spawn
    private void OnServerResponse(MatchmakingResponse resp, NetworkConnection sender)
    {
        if (!resp.accepted)
        {
            LobbyUI.ShowRejected();
            return;
        }

        PlayerPrefs.SetInt("AssignedTeam",  resp.assignedTeam);
        PlayerPrefs.SetInt("SpawnIndex",    resp.spawnPointIndex);
        LobbyUI.ShowReady(resp.assignedTeam);
    }
}

Use broadcasts for lobby and pre-spawn data

Spawned NetworkBehaviour objects are only available after the server creates them. Anything that must happen before spawning — team selection, loadout choice, authentication tokens — belongs in a broadcast, not an RPC. Move to RPCs once objects exist.

Broadcasts are not filtered by visibility

Unlike RPCs that respect the Network Visibility system, BroadcastAll sends to every connected client regardless of whether they should be observing a particular object. Apply your own application-level filtering (e.g. only relay chat to players in the same lobby) before calling BroadcastAll or route to specific connections with BroadcastConnection.