using System; using UnityEngine; using Unity.Collections; using Unity.Netcode; //自定义带名称的消息处理 public class CustomNamedMessageHandler : NetworkBehaviour { //类似于消息头 [Tooltip("用于消息处理的标志")] public string MessageName = "CustomNamedMessage"; public override void OnNetworkSpawn() { //注册带消息的处理回调,此处是ReceiveMessage方法 //此处是与CustomUnnamedMessageHandler不同的地方。CustomUnnamedMessageHandler使用如下方式注册 //NetworkManager.CustomMessagingManager.OnUnnamedMessage += ReceiveMessage; NetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(MessageName, ReceiveMessage); if(IsServer) { NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback; } else { //测试,客户端发送一个Guid SendMessage(Guid.NewGuid()); } } private void OnClientConnectedCallback(ulong obj) { SendMessage(Guid.NewGuid()); } public override void OnNetworkDespawn() { NetworkManager.CustomMessagingManager.UnregisterNamedMessageHandler(MessageName); NetworkManager.OnClientConnectedCallback -= OnClientConnectedCallback; } //收到消息 private void ReceiveMessage(ulong senderId, FastBufferReader messagePayload) { //处理接收的数据,用ForceNetworkSerializeByMemcpy进行序列化和反序列化,此处消息是个Guid var receivedMessageContent = new ForceNetworkSerializeByMemcpy(new Guid()); messagePayload.ReadValueSafe(out receivedMessageContent); if(IsServer) { Debug.Log($"Sever received GUID ({receivedMessageContent.Value}) from client ({senderId})"); } else { Debug.Log($"Client received GUID ({receivedMessageContent.Value}) from the server."); } } //发送自定义消息 public void SendMessage(Guid inGameIdentifier) { var messageContent = new ForceNetworkSerializeByMemcpy(inGameIdentifier); var writer = new FastBufferWriter(1100, Allocator.Temp); var customMessagingManager = NetworkManager.CustomMessagingManager; using(writer) { //写入消息 writer.WriteValueSafe(messageContent); if(IsServer) { //发送给所有客户端,某个MessageName的消息处理器 customMessagingManager.SendNamedMessageToAll(MessageName, writer); } else { //发送给某个客户端 customMessagingManager.SendNamedMessage(MessageName, NetworkManager.ServerClientId, writer); } } } }