Network Messages

To send simple custom network messages you can use the functions that are inside

TheNetwork.Get().Messaging...

These functions are using Netcode's NamedMessage in the background, but adds some extra validations.

For networked objects it is recommended to NOT use direct messages, and instead use the SNetworkActions which will save you a lot of lines of code. Direct messages can be used inside generic managers or for initialization.

ListenMsg and UnlistenMsg

Use ListenMsg("id", callback) to listen for incoming network messages.

Messaging.ListenMsg("attack", ReceiveAttack);
Messaging.UnlistenMsg("attack");
private void ReceiveAttack(ulong client_id, FastBufferReader reader)
{
    reader.ReadValueSafe(out int damage);
    ...
}

Send vs SendAll

Send allows you to send the message to a client of your choice (if called from the server) or to send to the server (if called from client).

SendAll can only be called from the server and will send to all connected clients.

SendInt, SendBool, SendFloat, SendBytes...

These function are used to send basic types as the only data in the message.

private void Attack(int damage)
{
    Messaging.SendIntAll("attack", damage, NetworkDelivery.Reliable);
}

SendObject

To send any class or struct (must inherit from INetworkSerializable). See original Netcode documentation to understand serialization: INetworkSerializable

Note that it is not possible to send GameObjects or class that contain non-serializable fields.

private void Attack(AttackData attack_data)
{
    Messaging.SendObjectAll("attack", attack_data, NetworkDelivery.Reliable);
}

SendBuffer

Use this function to send a FastBufferWriter, this is the original Netcode way to use namedMessages. Make sure to Dispose() the buffer if you created a new one.

private void Attack(AttackData attack_data, int damage)
{
    FastBufferWriter writer = new FastBufferWriter(128, Allocator.Temp, TheNetwork.MsgSizeMax);
    writer.WriteNetworkSerializable(attack_data);
    writer.WriteValueSafe(damage);
    Messaging.SendBufferAll("attack", writer, NetworkDelivery.Reliable);
    writer.Dispose();
}

Forward and ForwardAll

Forward should only be called by the server. And allows you to resend a message you receive from a client to another client (or to all other clients).

Last updated