forked from tmokmss/com.unity.multiplayer.samples.coop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkedMessageChannel.cs
89 lines (79 loc) · 2.71 KB
/
NetworkedMessageChannel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using VContainer;
namespace Unity.BossRoom.Infrastructure
{
/// <summary>
/// This type of message channel allows the server to publish a message that will be sent to clients as well as
/// being published locally. Clients and the server both can subscribe to it.
/// </summary>
/// <typeparam name="T"></typeparam>
public class NetworkedMessageChannel<T> : MessageChannel<T> where T : unmanaged, INetworkSerializeByMemcpy
{
NetworkManager m_NetworkManager;
string m_Name;
public NetworkedMessageChannel()
{
m_Name = $"{typeof(T).FullName}NetworkMessageChannel";
}
[Inject]
void InjectDependencies(NetworkManager networkManager)
{
m_NetworkManager = networkManager;
m_NetworkManager.OnClientConnectedCallback += OnClientConnected;
if (m_NetworkManager.IsListening)
{
RegisterHandler();
}
}
public override void Dispose()
{
if (!IsDisposed)
{
if (m_NetworkManager != null && m_NetworkManager.CustomMessagingManager != null)
{
m_NetworkManager.CustomMessagingManager.UnregisterNamedMessageHandler(m_Name);
}
}
base.Dispose();
}
void OnClientConnected(ulong clientId)
{
RegisterHandler();
}
void RegisterHandler()
{
// Only register message handler on clients
if (!m_NetworkManager.IsServer)
{
m_NetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(m_Name, ReceiveMessageThroughNetwork);
}
}
public override void Publish(T message)
{
if (m_NetworkManager.IsServer)
{
// send message to clients, then publish locally
SendMessageThroughNetwork(message);
base.Publish(message);
}
else
{
Debug.LogError("Only a server can publish in a NetworkedMessageChannel");
}
}
void SendMessageThroughNetwork(T message)
{
var writer = new FastBufferWriter(FastBufferWriter.GetWriteSize<T>(), Allocator.Temp);
writer.WriteValueSafe(message);
m_NetworkManager.CustomMessagingManager.SendNamedMessageToAll(m_Name, writer);
}
void ReceiveMessageThroughNetwork(ulong clientID, FastBufferReader reader)
{
reader.ReadValueSafe(out T message);
base.Publish(message);
}
}
}