Skip to content

Commit e44d423

Browse files
committed
Merge branch 'release/GDC2022' into sam/fix/workaround-loading-screen-not-going-away
* release/GDC2022: fix: leaving lobby when disconnecting (#515) better error messages and lobby fix (#550) feat: authentication failure message popups will tell the user to try direct ip connection option (#547) feat: replace guid with auth playerid for session management (#488) (#548) # Conflicts: # Assets/BossRoom/Scripts/Shared/Net/ConnectionManagement/ClientGameNetPortal.cs
2 parents 2790757 + 93ff764 commit e44d423

20 files changed

+316
-180
lines changed

Assets/BossRoom/Scenes/Startup.unity

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
version https://git-lfs.github.com/spec/v1
2-
oid sha256:dc7f49af8b674af05f84b82125472cba81519e43c16de951dfda618a3884c681
3-
size 44733
2+
oid sha256:225b7ddef7979d1165b3bb8cbbc709fc6bcf97367370b4b1bfe16d74919bbf74
3+
size 44138

Assets/BossRoom/Scripts/Client/Game/State/ClientMainMenuState.cs

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
using BossRoom.Scripts.Shared.Net.UnityServices.Auth;
2+
using Unity.Multiplayer.Samples.BossRoom.Shared;
23
using Unity.Multiplayer.Samples.BossRoom.Shared.Infrastructure;
34
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Lobbies;
45
using Unity.Multiplayer.Samples.BossRoom.Visual;
56
using Unity.Services.Authentication;
67
using Unity.Services.Core;
78
using UnityEngine;
89

9-
#if UNITY_EDITOR
10-
using ParrelSync;
11-
#endif
1210

1311
namespace Unity.Multiplayer.Samples.BossRoom.Client
1412
{
@@ -21,7 +19,6 @@ namespace Unity.Multiplayer.Samples.BossRoom.Client
2119
/// </remarks>
2220
public class ClientMainMenuState : GameStateBehaviour
2321
{
24-
public const string AuthProfileCommandLineArg = "-AuthProfile";
2522
public override GameState ActiveState { get { return GameState.MainMenu; } }
2623

2724
[SerializeField] GameObject[] m_GameObjectsThatWillBeInjectedAutomatically;
@@ -51,33 +48,11 @@ void InjectDependenciesAndInitialize(AuthenticationServiceFacade authServiceFaca
5148
m_Scope.BindInstanceAsSingle(m_IPUIMediator);
5249

5350
var unityAuthenticationInitOptions = new InitializationOptions();
54-
55-
#if UNITY_EDITOR
56-
//The code below makes it possible for the clone instance to log in as a different user profile in Authentication service.
57-
//This allows us to test services integration locally by utilising Parrelsync.
58-
if (ClonesManager.IsClone())
59-
{
60-
Debug.Log("This is a clone project.");
61-
var customArguments = ClonesManager.GetArgument().Split(',');
62-
63-
//second argument is our custom ID, but if it's not set we would just use some default.
64-
65-
var hardcodedProfileID = customArguments.Length > 1 ? customArguments[1] : "defaultCloneID";
66-
67-
unityAuthenticationInitOptions.SetProfile(hardcodedProfileID);
68-
}
69-
#else
70-
var arguments = System.Environment.GetCommandLineArgs();
71-
for (int i = 0; i < arguments.Length; i++)
51+
var profile = ProfileManager.Profile;
52+
if (profile.Length > 0)
7253
{
73-
if (arguments[i] == AuthProfileCommandLineArg)
74-
{
75-
var profileId = arguments[i + 1];
76-
unityAuthenticationInitOptions.SetProfile(profileId);
77-
break;
78-
}
54+
unityAuthenticationInitOptions.SetProfile(profile);
7955
}
80-
#endif
8156

8257
authServiceFacade.DoSignInAsync(OnAuthSignIn, OnSignInFailed, unityAuthenticationInitOptions);
8358

@@ -103,7 +78,6 @@ void OnAuthSignIn()
10378
void OnSignInFailed()
10479
{
10580
m_SignInSpinner.SetActive(false);
106-
PopupPanel.ShowPopupPanel("Authentication Error", "For some reason we can't authenticate the user anonymously - that typically means that project is not properly set up with Unity services.");
10781
}
10882
}
10983

Assets/BossRoom/Scripts/Client/UI/PopupPanel.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,7 @@ long SetupPopupPanel(string titleText, string mainText, bool isCloseableByUser =
9393
{
9494
if (m_IsPopupShown)
9595
{
96-
Debug.Log("Trying to show popup, but another popup is already being shown.");
97-
Debug.Log($"{titleText}. {mainText}");
96+
Debug.LogWarning($"Trying to show popup, but another popup is already being shown. Popup: {titleText}. {mainText}");
9897
return -1;
9998
}
10099

Assets/BossRoom/Scripts/Client/UI/UnityServicesUIHandler.cs

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
using System;
2-
using Unity.Multiplayer.Samples.BossRoom.Client;
2+
using Unity.Multiplayer.Samples.BossRoom.Shared;
33
using Unity.Multiplayer.Samples.BossRoom.Shared.Infrastructure;
44
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Infrastructure;
55
using Unity.Services.Lobbies;
@@ -25,18 +25,33 @@ void Initialize(ISubscriber<UnityServiceErrorMessage> serviceError)
2525
void ServiceErrorHandler(UnityServiceErrorMessage error)
2626
{
2727
var errorMessage = error.Message;
28-
if (error.AffectedService == UnityServiceErrorMessage.Service.Lobby)
28+
switch (error.AffectedService)
2929
{
30-
if (error.OriginalException is LobbyServiceException {Reason: LobbyExceptionReason.LobbyConflict})
30+
case UnityServiceErrorMessage.Service.Lobby:
3131
{
32-
// LobbyConflict can have multiple causes. Let's add other solutions here if there's other situations that arise for this.
33-
errorMessage += "\nSee logs for possible causes and solution.";
34-
Debug.LogError($"Got service error {error.Message} with LobbyConflict. Possible conflict cause: Trying to play with two builds on the " +
35-
$"same machine. Please use command line arg '{ClientMainMenuState.AuthProfileCommandLineArg} someName' to set a different auth profile.\n");
32+
if ((error.OriginalException is LobbyServiceException {Reason: LobbyExceptionReason.LobbyConflict}))
33+
{
34+
// LobbyConflict can have multiple causes. Let's add other solutions here if there's other situations that arise for this.
35+
errorMessage += "\nSee logs for possible causes and solution.";
36+
Debug.LogError($"Got service error {error.Message} with LobbyConflict. Possible conflict cause: Trying to play with two builds on the " +
37+
$"same machine. Please use command line arg '{ProfileManager.AuthProfileCommandLineArg} someName' to set a different auth profile.\n");
38+
}
39+
PopupPanel.ShowPopupPanel("Service error", errorMessage);
40+
break;
41+
}
42+
case UnityServiceErrorMessage.Service.Authentication:
43+
{
44+
PopupPanel.ShowPopupPanel(
45+
"Authentication Error",
46+
$"{error.OriginalException.Message} \n tip: You can still use the Direct IP connection option.");
47+
break;
48+
}
49+
default:
50+
{
51+
PopupPanel.ShowPopupPanel("Service error: "+error.Title, errorMessage);
52+
break;
3653
}
3754
}
38-
39-
PopupPanel.ShowPopupPanel("Service error", errorMessage);
4055
}
4156

4257
void OnDestroy()

Assets/BossRoom/Scripts/Client/com.unity.multiplayer.samples.bossroom.client.asmdef

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
"Photon Realtime Transport for Netcode for GameObjects",
1313
"Unity.Services.Relay",
1414
"Unity.Multiplayer.Samples.Utilities",
15-
"Unity.Services.Lobbies",
16-
"ParrelSync"
15+
"Unity.Services.Lobbies"
1716
],
1817
"includePlatforms": [],
1918
"excludePlatforms": [],
@@ -24,4 +23,4 @@
2423
"defineConstraints": [],
2524
"versionDefines": [],
2625
"noEngineReferences": false
27-
}
26+
}

Assets/BossRoom/Scripts/Shared/ApplicationController.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Collections;
22
using BossRoom.Scripts.Shared.Net.UnityServices.Auth;
33
using Unity.Multiplayer.Samples.BossRoom.Client;
4+
using Unity.Multiplayer.Samples.BossRoom.Server;
45
using Unity.Multiplayer.Samples.BossRoom.Shared.Infrastructure;
56
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Infrastructure;
67
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Lobbies;
@@ -19,6 +20,7 @@ public class ApplicationController : MonoBehaviour
1920
[SerializeField] UpdateRunner m_UpdateRunner;
2021
[SerializeField] GameNetPortal m_GameNetPortal;
2122
[SerializeField] ClientGameNetPortal m_ClientNetPortal;
23+
[SerializeField] ServerGameNetPortal m_ServerGameNetPortal;
2224

2325
LocalLobby m_LocalLobby;
2426
LobbyServiceFacade m_LobbyServiceFacade;
@@ -38,6 +40,7 @@ private void Awake()
3840
scope.BindInstanceAsSingle(m_UpdateRunner);
3941
scope.BindInstanceAsSingle(m_GameNetPortal);
4042
scope.BindInstanceAsSingle(m_ClientNetPortal);
43+
scope.BindInstanceAsSingle(m_ServerGameNetPortal);
4144

4245
//the following singletons represent the local representations of the lobby that we're in and the user that we are
4346
//they can persist longer than the lifetime of the UI in MainMenu where we set up the lobby that we create or join

Assets/BossRoom/Scripts/Shared/ClientPrefs.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ namespace Unity.Multiplayer.Samples.BossRoom.Client
77
/// (This is just a wrapper around the PlayerPrefs system,
88
/// so that all the calls are in the same place.)
99
/// </summary>
10-
public class ClientPrefs
10+
public static class ClientPrefs
1111
{
12-
private const float k_DefaultMasterVolume = 0.5f;
13-
private const float k_DefaultMusicVolume = 0.8f;
12+
const float k_DefaultMasterVolume = 0.5f;
13+
const float k_DefaultMusicVolume = 0.8f;
1414

1515
public static float GetMasterVolume()
1616
{

Assets/BossRoom/Scripts/Shared/Net/ConnectionManagement/ClientGameNetPortal.cs

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections;
3+
using Unity.Multiplayer.Samples.BossRoom.Shared;
34
using Unity.Multiplayer.Samples.BossRoom.Shared.Infrastructure;
45
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Lobbies;
56
using UnityEngine;
@@ -39,12 +40,14 @@ public class ClientGameNetPortal : MonoBehaviour
3940
/// </summary>
4041
public event Action NetworkTimedOut;
4142

42-
private LobbyServiceFacade m_LobbyServiceFacade;
43+
ApplicationController m_ApplicationController;
44+
LobbyServiceFacade m_LobbyServiceFacade;
4345
IPublisher<ConnectStatus> m_ConnectStatusPub;
4446

4547
[Inject]
46-
private void InjectDependencies(LobbyServiceFacade lobbyServiceFacade, IPublisher<ConnectStatus> connectStatusPub)
48+
private void InjectDependencies(ApplicationController applicationController, LobbyServiceFacade lobbyServiceFacade, IPublisher<ConnectStatus> connectStatusPub)
4749
{
50+
m_ApplicationController = applicationController;
4851
m_LobbyServiceFacade = lobbyServiceFacade;
4952
m_ConnectStatusPub = connectStatusPub;
5053
}
@@ -150,23 +153,28 @@ void OnDisconnectOrTimeout(ulong clientID)
150153
{
151154
SceneLoaderWrapper.Instance.IsClosingClients = false; // disconnect done
152155

156+
var lobbyCode = "";
157+
if (m_LobbyServiceFacade.CurrentUnityLobby != null)
158+
{
159+
lobbyCode = m_LobbyServiceFacade.CurrentUnityLobby.LobbyCode;
160+
}
161+
153162
//On a client disconnect we want to take them back to the main menu.
154163
//We have to check here in SceneManager if our active scene is the main menu, as if it is, it means we timed out rather than a raw disconnect;
155164
if (SceneManager.GetActiveScene().name != "MainMenu")
156165
{
157166
if (DisconnectReason.Reason == ConnectStatus.UserRequestedDisconnect || DisconnectReason.Reason == ConnectStatus.HostDisconnected || NetworkManager.Singleton.IsHost)
158167
{
159168
// simply shut down and go back to main menu
160-
NetworkManager.Singleton.Shutdown();
161-
SceneLoaderWrapper.Instance.LoadScene("MainMenu");
169+
m_ApplicationController.LeaveSession();
162170
}
163171
else
164172
{
165173
DisconnectReason.SetDisconnectReason(ConnectStatus.Reconnecting);
166174
// load new scene to workaround MTT-2684
167175
SceneManager.LoadScene("Loading");
168176
// try reconnecting
169-
m_TryToReconnectCoroutine ??= StartCoroutine(TryToReconnect());
177+
m_TryToReconnectCoroutine ??= StartCoroutine(TryToReconnect(lobbyCode));
170178
}
171179
}
172180
else if (DisconnectReason.Reason == ConnectStatus.GenericDisconnect || DisconnectReason.Reason == ConnectStatus.Undefined)
@@ -180,7 +188,7 @@ void OnDisconnectOrTimeout(ulong clientID)
180188
}
181189
}
182190

183-
private IEnumerator TryToReconnect()
191+
private IEnumerator TryToReconnect(string lobbyCode)
184192
{
185193
Debug.Log("Lost connection to host, trying to reconnect...");
186194
int nbTries = 0;
@@ -189,13 +197,29 @@ private IEnumerator TryToReconnect()
189197
NetworkManager.Singleton.Shutdown();
190198
yield return new WaitWhile(() => NetworkManager.Singleton.ShutdownInProgress); // wait until NetworkManager completes shutting down
191199
Debug.Log($"Reconnecting attempt {nbTries + 1}/{k_NbReconnectAttempts}...");
192-
ConnectClient(null);
200+
if (!string.IsNullOrEmpty(lobbyCode))
201+
{
202+
var leavingLobby = m_LobbyServiceFacade.EndTracking();
203+
yield return new WaitUntil(() => leavingLobby.IsCompleted);
204+
var joiningLobby = m_LobbyServiceFacade.JoinLobbyAsync("", lobbyCode, onSuccess: lobby =>
205+
{
206+
m_LobbyServiceFacade.BeginTracking(lobby);
207+
ConnectClient(null);
208+
}
209+
, null);
210+
yield return new WaitUntil(() => joiningLobby.IsCompleted);
211+
}
212+
else
213+
{
214+
ConnectClient(null);
215+
}
193216
yield return new WaitForSeconds(1.1f * k_TimeoutDuration); // wait a bit longer than the timeout duration to make sure we have enough time to stop this coroutine if successful
194217
nbTries++;
195218
}
196219

197220
// If the coroutine has not been stopped before this, it means we failed to connect during all attempts
198221
Debug.Log("All tries failed, returning to main menu");
222+
m_LobbyServiceFacade.ForceLeaveLobbyAttempt();
199223
NetworkManager.Singleton.Shutdown();
200224
SceneLoaderWrapper.Instance.LoadScene("MainMenu");
201225
if (!DisconnectReason.HasTransitionReason)
@@ -271,10 +295,9 @@ async void ConnectClient(Action<string> onFailure)
271295
}
272296
}
273297

274-
var clientGuid = ClientPrefs.GetGuid();
275298
var payload = JsonUtility.ToJson(new ConnectionPayload()
276299
{
277-
clientGUID = clientGuid,
300+
playerId = m_Portal.GetPlayerId(),
278301
clientScene = SceneManager.GetActiveScene().buildIndex,
279302
playerName = m_Portal.PlayerName
280303
});

Assets/BossRoom/Scripts/Shared/Net/ConnectionManagement/GameNetPortal.cs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
using System;
2-
using System.Collections;
32
using Unity.Multiplayer.Samples.BossRoom.Client;
43
using Unity.Multiplayer.Samples.BossRoom.Server;
4+
using Unity.Multiplayer.Samples.BossRoom.Shared;
55
using Unity.Multiplayer.Samples.BossRoom.Shared.Infrastructure;
66
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Lobbies;
77
using Unity.Netcode;
88
using Unity.Netcode.Transports.UNET;
9+
using Unity.Services.Authentication;
910
using UnityEngine;
1011
using UnityEngine.SceneManagement;
1112

@@ -34,7 +35,7 @@ public enum OnlineMode
3435
[Serializable]
3536
public class ConnectionPayload
3637
{
37-
public string clientGUID;
38+
public string playerId;
3839
public int clientScene = -1;
3940
public string playerName;
4041
}
@@ -107,7 +108,6 @@ private void Awake()
107108

108109
//we synthesize a "OnNetworkSpawn" event for the NetworkManager out of existing events. At some point
109110
//we expect NetworkManager will expose an event like this itself.
110-
NetManager.OnServerStarted += OnNetworkReady;
111111
NetManager.OnClientConnectedCallback += ClientNetworkReadyWrapper;
112112
}
113113

@@ -123,7 +123,6 @@ private void OnDestroy()
123123
{
124124
if (NetManager != null)
125125
{
126-
NetManager.OnServerStarted -= OnNetworkReady;
127126
NetManager.OnClientConnectedCallback -= ClientNetworkReadyWrapper;
128127
}
129128

@@ -248,5 +247,10 @@ public void RequestDisconnect()
248247
m_ClientPortal.OnUserDisconnectRequest();
249248
m_ServerPortal.OnUserDisconnectRequest();
250249
}
250+
251+
public string GetPlayerId()
252+
{
253+
return AuthenticationService.Instance.IsSignedIn ? AuthenticationService.Instance.PlayerId : ClientPrefs.GetGuid() + ProfileManager.Profile;
254+
}
251255
}
252256
}

0 commit comments

Comments
 (0)