Redirection

Netcode for GameObjects is built on the principle of server authorization, which has its advantages and disadvantages. When using RPCs, I can be confident that I received the RPC from a client if I am the server, or from the server if I am the client.

Messages also support this assurance by default. However, there are scenarios where you may need to bypass this, such as when creating a chat system that allows private messages between clients. This is easily achievable with Messages by adding a true parameter to the [Message] attribute.

How does it work?

It works by redirecting the message to the server if it can't be sent directly (for example, from client 1 to client 2). The server then checks if this action is permitted. If it is, the server forwards the message to client 2, allowing client 2 to recognize that it was sent by client 1.

IMPORTANT: This introduces some vulnerabilities! We can't assume that a message comes from the server when redirection is enabled, as it allows any client to send messages to any other client.

Example

Let's use our good old ‘hello’ message again for this example as well!

private void Start()
{
    // This is called on every client when they join!
    NetworkManager.Singleton.OnClientStarted += () =>
    {
        // Normally sending a message to everyone is only a thing for the server to do!
        // Let's say hello to everyone when we join!
        Messenger.ToAll(HelloMessage);
    };
}

[Message(allowRedirect:true)]
private void HelloMessage(ulong senderId)
{
    Debug.Log($"{senderId} says hello!");
}

If you want more examples please go to the samples page.

Last updated