Getting Started

How does it work?

Messenger operates by leveraging Netcode for GameObjects' custom messaging feature. When a message is sent, it’s serialized into a JSON string (serialization details are explained on the Serialization page). The message is then routed through the Custom Messaging Manager. Once the target receives it, the message is deserialized, checks if redirection is necessary (covered further on the Redirection page), and, using its Message ID, locates and executes the correct method.

How can i create my own message?

Similar to RPCs, you can create custom methods using the [Message] attribute on any method you choose. Each message method requires its first argument to be a ulong parameter, representing the sender's ID. Beyond that, you can add between 0 and 15 parameters, which should cover most use cases. If more parameters are needed, consider combining them into a single class. Here’s an example of a message method below.

Basic Message

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

Underscore naming

If the senderId feels like it clutters your code, especially when it’s not needed for your message, you can use an underscore _ to indicate that the variable is intentionally ignored. This is a good practice to keep your code clean and focused!

[Message]
private void HelloMessage(ulong _)
{
    Debug.Log($"Someone unkown says hello!");
}

Async support

Did I mention messages support async as well?

[Message]
private async void HelloMessage(ulong _)
{
    Debug.Log("Waiting to say hello...");
    await Task.Delay(1234); // 1.234 seconds
    Debug.Log($"Someone unkown says hello!");
}

Message calling in message

Or, how about sending a ‘hello’ message to our fell wo neighbour player to keep the game atmosphere warm and welcoming?

[Message(true)]
private async void HelloMessage(ulong _)
{
    Debug.Log("Waiting to say hello...");
    await Task.Delay(1234); // 1.234 seconds
    Debug.Log($"Someone unkown says hello!");
    
    // Sends the ‘hello’ message to the next player.
    // Yes, I know this won’t work for the last player, but this is an example.
    Messenger.To(HelloMessage, MultiplayerUtils.LocalClientId + 1);
}

Notice that I included a true parameter in the [Message] attribute. This enables redirection for the message. For more details on how redirection works, check out the Redirection page.

Last updated