CustomNamedMessageHandler.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using UnityEngine;
  3. using Unity.Collections;
  4. using Unity.Netcode;
  5. //自定义带名称的消息处理
  6. public class CustomNamedMessageHandler : NetworkBehaviour
  7. {
  8. //类似于消息头
  9. [Tooltip("用于消息处理的标志")]
  10. public string MessageName = "CustomNamedMessage";
  11. public override void OnNetworkSpawn()
  12. {
  13. //注册带消息的处理回调,此处是ReceiveMessage方法
  14. //此处是与CustomUnnamedMessageHandler不同的地方。CustomUnnamedMessageHandler使用如下方式注册
  15. //NetworkManager.CustomMessagingManager.OnUnnamedMessage += ReceiveMessage;
  16. NetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(MessageName, ReceiveMessage);
  17. if(IsServer)
  18. {
  19. NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback;
  20. }
  21. else
  22. {
  23. //测试,客户端发送一个Guid
  24. SendMessage(Guid.NewGuid());
  25. }
  26. }
  27. private void OnClientConnectedCallback(ulong obj)
  28. {
  29. SendMessage(Guid.NewGuid());
  30. }
  31. public override void OnNetworkDespawn()
  32. {
  33. NetworkManager.CustomMessagingManager.UnregisterNamedMessageHandler(MessageName);
  34. NetworkManager.OnClientConnectedCallback -= OnClientConnectedCallback;
  35. }
  36. //收到消息
  37. private void ReceiveMessage(ulong senderId, FastBufferReader messagePayload)
  38. {
  39. //处理接收的数据,用ForceNetworkSerializeByMemcpy进行序列化和反序列化,此处消息是个Guid
  40. var receivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
  41. messagePayload.ReadValueSafe(out receivedMessageContent);
  42. if(IsServer)
  43. {
  44. Debug.Log($"Sever received GUID ({receivedMessageContent.Value}) from client ({senderId})");
  45. }
  46. else
  47. {
  48. Debug.Log($"Client received GUID ({receivedMessageContent.Value}) from the server.");
  49. }
  50. }
  51. //发送自定义消息
  52. public void SendMessage(Guid inGameIdentifier)
  53. {
  54. var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(inGameIdentifier);
  55. var writer = new FastBufferWriter(1100, Allocator.Temp);
  56. var customMessagingManager = NetworkManager.CustomMessagingManager;
  57. using(writer)
  58. {
  59. //写入消息
  60. writer.WriteValueSafe(messageContent);
  61. if(IsServer)
  62. {
  63. //发送给所有客户端,某个MessageName的消息处理器
  64. customMessagingManager.SendNamedMessageToAll(MessageName, writer);
  65. }
  66. else
  67. {
  68. //发送给某个客户端
  69. customMessagingManager.SendNamedMessage(MessageName, NetworkManager.ServerClientId, writer);
  70. }
  71. }
  72. }
  73. }