forked from Unity-Technologies/com.unity.netcode.gameobjects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionModeScript.cs
More file actions
291 lines (248 loc) · 9 KB
/
ConnectionModeScript.cs
File metadata and controls
291 lines (248 loc) · 9 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
using System.Collections;
using UnityEngine;
using Unity.Netcode;
#if ENABLE_RELAY_SERVICE
using System;
using Unity.Services.Core;
using Unity.Services.Authentication;
#endif
/// <summary>
/// Used in tandem with the ConnectModeButtons prefab asset in test project
/// </summary>
public class ConnectionModeScript : MonoBehaviour
{
[SerializeField]
private GameObject m_ConnectionModeButtons;
[SerializeField]
private GameObject m_AuthenticationButtons;
[SerializeField]
private GameObject m_JoinCodeInput;
[SerializeField]
private int m_MaxConnections = 10;
private CommandLineProcessor m_CommandLineProcessor;
[HideInInspector]
public string RelayJoinCode { get; set; }
internal void SetCommandLineHandler(CommandLineProcessor commandLineProcessor)
{
m_CommandLineProcessor = commandLineProcessor;
if (m_CommandLineProcessor.AutoConnectEnabled())
{
StartCoroutine(WaitForNetworkManager());
}
}
public delegate void OnNotifyConnectionEventDelegateHandler();
public event OnNotifyConnectionEventDelegateHandler OnNotifyConnectionEventServer;
public event OnNotifyConnectionEventDelegateHandler OnNotifyConnectionEventHost;
public event OnNotifyConnectionEventDelegateHandler OnNotifyConnectionEventClient;
private IEnumerator WaitForNetworkManager()
{
while (true)
{
yield return new WaitForSeconds(0.5f);
try
{
if (NetworkManager.Singleton && !NetworkManager.Singleton.IsListening)
{
m_ConnectionModeButtons.SetActive(false);
m_CommandLineProcessor.ProcessCommandLine();
break;
}
}
catch { }
}
yield return null;
}
/// <summary>
/// Check whether we are even using UnityTransport and
/// if so whether it is using the RelayUnityTransport
/// </summary>
private bool HasRelaySupport()
{
var unityTransport = NetworkManager.Singleton.GetComponent<UnityTransport>();
if (unityTransport != null && unityTransport.Protocol == UnityTransport.ProtocolType.RelayUnityTransport)
{
return true;
}
return false;
}
// Start is called before the first frame update
private void Start()
{
//If we have a NetworkManager instance and we are not listening and m_ConnectionModeButtons is not null then show the connection mode buttons
if (m_ConnectionModeButtons && m_AuthenticationButtons)
{
if (HasRelaySupport())
{
m_JoinCodeInput.SetActive(true);
//If Start() is called on the first frame update, it's not likely that the AuthenticationService is going to be instantiated yet
//Moved old logic for this out to OnServicesInitialized
m_ConnectionModeButtons.SetActive(false);
m_AuthenticationButtons.SetActive(true);
}
else
{
m_JoinCodeInput.SetActive(false);
m_AuthenticationButtons.SetActive(false);
m_ConnectionModeButtons.SetActive(NetworkManager.Singleton && !NetworkManager.Singleton.IsListening);
}
}
}
private void OnServicesInitialized()
{
if (HasRelaySupport())
{
m_JoinCodeInput.SetActive(true);
m_ConnectionModeButtons.SetActive(false || AuthenticationService.Instance.IsSignedIn);
m_AuthenticationButtons.SetActive(NetworkManager.Singleton && !NetworkManager.Singleton.IsListening && !AuthenticationService.Instance.IsSignedIn);
}
}
/// <summary>
/// Handles starting netcode in server mode
/// </summary>
public void OnStartServerButton()
{
if (NetworkManager.Singleton && !NetworkManager.Singleton.IsListening && m_ConnectionModeButtons)
{
if (HasRelaySupport())
{
StartCoroutine(StartRelayServer(StartServer));
}
else
{
StartServer();
}
}
}
private void StartServer()
{
NetworkManager.Singleton.StartServer();
OnNotifyConnectionEventServer?.Invoke();
m_ConnectionModeButtons.SetActive(false);
}
/// <summary>
/// Coroutine that handles starting MLAPI in server mode if Relay is enabled
/// </summary>
private IEnumerator StartRelayServer(Action postAllocationAction)
{
#if ENABLE_RELAY_SERVICE
m_ConnectionModeButtons.SetActive(false);
var serverRelayUtilityTask = RelayUtility.AllocateRelayServerAndGetJoinCode(m_MaxConnections);
while (!serverRelayUtilityTask.IsCompleted)
{
yield return null;
}
if (serverRelayUtilityTask.IsFaulted)
{
Debug.LogError("Exception thrown when attempting to start Relay Server. Server not started. Exception: " + serverRelayUtilityTask.Exception.Message);
yield break;
}
var (ipv4address, port, allocationIdBytes, connectionData, key, joinCode) = serverRelayUtilityTask.Result;
RelayJoinCode = joinCode;
//When starting a relay server, both instances of connection data are identical.
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(ipv4address, port, allocationIdBytes, key, connectionData);
postAllocationAction();
#else
yield return null;
#endif
}
/// <summary>
/// Handles starting netcode in host mode
/// </summary>
public void OnStartHostButton()
{
if (NetworkManager.Singleton && !NetworkManager.Singleton.IsListening && m_ConnectionModeButtons)
{
if (HasRelaySupport())
{
StartCoroutine(StartRelayServer(StartHost));
}
else
{
StartHost();
}
}
}
private void StartHost()
{
NetworkManager.Singleton.StartHost();
OnNotifyConnectionEventHost?.Invoke();
m_ConnectionModeButtons.SetActive(false);
}
/// <summary>
/// Handles starting netcode in client mode
/// </summary>
public void OnStartClientButton()
{
if (NetworkManager.Singleton && !NetworkManager.Singleton.IsListening && m_ConnectionModeButtons)
{
if (HasRelaySupport())
{
StartCoroutine(StartRelayClient());
}
else
{
StartClient();
}
}
}
private void StartClient()
{
NetworkManager.Singleton.StartClient();
OnNotifyConnectionEventClient?.Invoke();
m_ConnectionModeButtons.SetActive(false);
}
/// <summary>
/// Coroutine that kicks off Relay SDK calls to join a Relay Server instance with a join code
/// </summary>
/// <returns></returns>
private IEnumerator StartRelayClient()
{
#if ENABLE_RELAY_SERVICE
m_ConnectionModeButtons.SetActive(false);
//assumes that RelayJoinCodeInput populated RelayJoinCode prior to this
var clientRelayUtilityTask = RelayUtility.JoinRelayServerFromJoinCode(RelayJoinCode);
while (!clientRelayUtilityTask.IsCompleted)
{
yield return null;
}
if (clientRelayUtilityTask.IsFaulted)
{
Debug.LogError("Exception thrown when attempting to connect to Relay Server. Exception: " + clientRelayUtilityTask.Exception.Message);
yield break;
}
var (ipv4address, port, allocationIdBytes, connectionData, hostConnectionData, key) = clientRelayUtilityTask.Result;
//When connecting as a client to a relay server, connectionData and hostConnectionData are different.
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(ipv4address, port, allocationIdBytes, key, connectionData, hostConnectionData);
NetworkManager.Singleton.StartClient();
OnNotifyConnectionEventClient?.Invoke();
#else
yield return null;
#endif
}
// Will be used for Relay support when it becomes available.
// TODO: Remove this comment once relay support is available.
#if ENABLE_RELAY_SERVICE
/// <summary>
/// Handles authenticating UnityServices, needed for Relay
/// </summary>
public async void OnSignIn()
{
await UnityServices.InitializeAsync();
OnServicesInitialized();
await AuthenticationService.Instance.SignInAnonymouslyAsync();
Debug.Log($"Logging in with PlayerID {AuthenticationService.Instance.PlayerId}");
if (AuthenticationService.Instance.IsSignedIn)
{
m_ConnectionModeButtons.SetActive(true);
m_AuthenticationButtons.SetActive(false);
}
}
#endif
public void Reset()
{
if (NetworkManager.Singleton && !NetworkManager.Singleton.IsListening && m_ConnectionModeButtons)
{
m_ConnectionModeButtons.SetActive(true);
}
}
}