M
M
Mirror
Search…
Network Messages
For the most part we recommend the high level Commands and RPC calls and SyncVar, but you can also send low level network messages. This can be useful if you want clients to send messages that are not tied to game objects, such as logging, analytics or profiling information.
There is a public interface called NetworkMessage that you can extend to make serializable network message structs. This interface has Serialize and Deserialize functions that take writer and reader objects. You can implement these functions yourself, but we recommend you let Mirror generate them for you.
The auto generated Serialize/Deserialize can efficiently deal any supported mirror type. Make your members public. If you need classes or complex containers such as List and Dictionary, you must implement the Serialize and Deserialize methods yourself.
To send a message, use the Send() method on the NetworkClient, NetworkServer, and NetworkConnection classes, which all work the same way using a message struct that is derived from NetworkMessage. The code below demonstrates how to send and handle a message:
To declare a custom network message class and use it:
1
using UnityEngine;
2
using Mirror;
3
4
public class Scores : MonoBehaviour
5
{
6
public struct ScoreMessage : NetworkMessage
7
{
8
public int score;
9
public Vector3 scorePos;
10
public int lives;
11
}
12
13
public void SendScore(int score, Vector3 scorePos, int lives)
14
{
15
ScoreMessage msg = new ScoreMessage()
16
{
17
score = score,
18
scorePos = scorePos,
19
lives = lives
20
};
21
22
NetworkServer.SendToAll(msg);
23
}
24
25
public void SetupClient()
26
{
27
NetworkClient.RegisterHandler<ScoreMessage>(OnScore);
28
NetworkClient.Connect("localhost");
29
}
30
31
public void OnScore(ScoreMessage msg)
32
{
33
Debug.Log("OnScoreMessage " + msg.score);
34
}
35
}
Copied!
Note that there is no serialization code for the ScoreMessage class in this source code example. The body of the serialization functions is automatically generated for this class by Mirror.
Last modified 8mo ago
Copy link