Skip to content

Commit 46e2cef

Browse files
feat: replace guid with auth playerid for session management (#488)
* Replaced custom guid with playerid for session management when signed in through UGS's Authentication Service * Removed code handling duplicate connections in debug builds * When not using UGS, player id is now defined as GUID + profile string
1 parent 9244751 commit 46e2cef

File tree

11 files changed

+134
-128
lines changed

11 files changed

+134
-128
lines changed

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

Lines changed: 3 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,6 @@
66
using Unity.Services.Core;
77
using UnityEngine;
88

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

1310
namespace Unity.Multiplayer.Samples.BossRoom.Client
1411
{
@@ -21,7 +18,6 @@ namespace Unity.Multiplayer.Samples.BossRoom.Client
2118
/// </remarks>
2219
public class ClientMainMenuState : GameStateBehaviour
2320
{
24-
public const string AuthProfileCommandLineArg = "-AuthProfile";
2521
public override GameState ActiveState { get { return GameState.MainMenu; } }
2622

2723
[SerializeField] GameObject[] m_GameObjectsThatWillBeInjectedAutomatically;
@@ -51,33 +47,11 @@ void InjectDependenciesAndInitialize(AuthenticationServiceFacade authServiceFaca
5147
m_Scope.BindInstanceAsSingle(m_IPUIMediator);
5248

5349
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++)
50+
var profile = ProfileManager.Profile;
51+
if (profile.Length > 0)
7252
{
73-
if (arguments[i] == AuthProfileCommandLineArg)
74-
{
75-
var profileId = arguments[i + 1];
76-
unityAuthenticationInitOptions.SetProfile(profileId);
77-
break;
78-
}
53+
unityAuthenticationInitOptions.SetProfile(profile);
7954
}
80-
#endif
8155

8256
authServiceFacade.DoSignInAsync(OnAuthSignIn, OnSignInFailed, unityAuthenticationInitOptions);
8357

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ void ServiceErrorHandler(UnityServiceErrorMessage error)
3434
// LobbyConflict can have multiple causes. Let's add other solutions here if there's other situations that arise for this.
3535
errorMessage += "\nSee logs for possible causes and solution.";
3636
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 '{ClientMainMenuState.AuthProfileCommandLineArg} someName' to set a different auth profile.\n");
37+
$"same machine. Please use command line arg '{ProfileManager.AuthProfileCommandLineArg} someName' to set a different auth profile.\n");
3838
}
3939
}
4040
}
@@ -47,4 +47,4 @@ void OnDestroy()
4747
m_Subscriptions.Dispose();
4848
}
4949
}
50-
}
50+
}

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
@@ -11,8 +11,7 @@
1111
"Unity.Netcode.Adapter.UTP",
1212
"Unity.Services.Relay",
1313
"Unity.Multiplayer.Samples.Utilities",
14-
"Unity.Services.Lobbies",
15-
"ParrelSync"
14+
"Unity.Services.Lobbies"
1615
],
1716
"includePlatforms": [],
1817
"excludePlatforms": [],
@@ -23,4 +22,4 @@
2322
"defineConstraints": [],
2423
"versionDefines": [],
2524
"noEngineReferences": false
26-
}
25+
}

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: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using Unity.Multiplayer.Samples.BossRoom.Shared.Infrastructure;
3-
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Infrastructure;
43
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Lobbies;
54
using UnityEngine;
65
using UnityEngine.SceneManagement;
@@ -155,7 +154,6 @@ private void OnDisconnectOrTimeout(ulong clientID)
155154
/// This method must be static because, when it is invoked, the client still doesn't know it's a client yet, and in particular, GameNetPortal hasn't
156155
/// yet initialized its client and server GameNetPortal objects yet (which it does in OnNetworkSpawn, based on the role that the current player is performing).
157156
/// </remarks>
158-
/// <param name="portal"> </param>
159157
/// <param name="ipaddress">the IP address of the host to connect to. (currently IPV4 only)</param>
160158
/// <param name="port">The port of the host to connect to. </param>
161159
public void StartClient(string ipaddress, int port)
@@ -202,15 +200,16 @@ public async void StartClientUnityRelayModeAsync(string joinCode, Action<string>
202200
return;//not re-throwing, but still not allowing to connect
203201
}
204202

203+
205204
ConnectClient();
206205
}
207206

208-
private void ConnectClient()
207+
void ConnectClient()
209208
{
210-
var clientGuid = ClientPrefs.GetGuid();
209+
211210
var payload = JsonUtility.ToJson(new ConnectionPayload()
212211
{
213-
clientGUID = clientGuid,
212+
playerId = m_Portal.GetPlayerId(),
214213
clientScene = SceneManager.GetActiveScene().buildIndex,
215214
playerName = m_Portal.PlayerName
216215
});

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using Unity.Multiplayer.Samples.BossRoom.Shared.Net.UnityServices.Lobbies;
66
using Unity.Netcode;
77
using Unity.Netcode.Transports.UNET;
8+
using Unity.Services.Authentication;
89
using UnityEngine;
910
using UnityEngine.SceneManagement;
1011

@@ -31,7 +32,7 @@ public enum OnlineMode
3132
[Serializable]
3233
public class ConnectionPayload
3334
{
34-
public string clientGUID;
35+
public string playerId;
3536
public int clientScene = -1;
3637
public string playerName;
3738
}
@@ -245,5 +246,10 @@ public void RequestDisconnect()
245246
SessionManager<SessionPlayerData>.Instance.OnUserDisconnectRequest();
246247
NetManager.Shutdown();
247248
}
249+
250+
public string GetPlayerId()
251+
{
252+
return AuthenticationService.Instance.IsSignedIn ? AuthenticationService.Instance.PlayerId : ClientPrefs.GetGuid() + ProfileManager.Profile;
253+
}
248254
}
249255
}

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ private void ApprovalCheck(byte[] connectionData, ulong clientId, NetworkManager
146146
// Approval check happens for Host too, but obviously we want it to be approved
147147
if (clientId == NetworkManager.Singleton.LocalClientId)
148148
{
149-
SessionManager<SessionPlayerData>.Instance.AddHostData(
149+
SessionManager<SessionPlayerData>.Instance.SetupConnectingPlayerSessionData(clientId, m_Portal.GetPlayerId(),
150150
new SessionPlayerData(clientId, m_Portal.PlayerName, m_Portal.AvatarRegistry.GetRandomAvatar().Guid.ToNetworkGuid(), 0, true));
151151

152152
connectionApprovedCallback(true, null, true, null, null);
@@ -176,9 +176,9 @@ private void ApprovalCheck(byte[] connectionData, ulong clientId, NetworkManager
176176

177177
int clientScene = connectionPayload.clientScene;
178178

179-
Debug.Log("Host ApprovalCheck: connecting client GUID: " + connectionPayload.clientGUID);
179+
Debug.Log("Host ApprovalCheck: connecting client with player ID: " + connectionPayload.playerId);
180180

181-
gameReturnStatus = SessionManager<SessionPlayerData>.Instance.SetupConnectingPlayerSessionData(clientId, connectionPayload.clientGUID,
181+
gameReturnStatus = SessionManager<SessionPlayerData>.Instance.SetupConnectingPlayerSessionData(clientId, connectionPayload.playerId,
182182
new SessionPlayerData(clientId, connectionPayload.playerName, m_Portal.AvatarRegistry.GetRandomAvatar().Guid.ToNetworkGuid(), 0, true))
183183
? ConnectStatus.Success
184184
: ConnectStatus.LoggedInAgain;
@@ -187,7 +187,7 @@ private void ApprovalCheck(byte[] connectionData, ulong clientId, NetworkManager
187187
if (gameReturnStatus == ConnectStatus.LoggedInAgain)
188188
{
189189
SessionPlayerData? sessionPlayerData =
190-
SessionManager<SessionPlayerData>.Instance.GetPlayerData(connectionPayload.clientGUID);
190+
SessionManager<SessionPlayerData>.Instance.GetPlayerData(connectionPayload.playerId);
191191

192192
ulong oldClientId = sessionPlayerData?.ClientID ?? 0;
193193
// kicking old client to leave only current
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
using UnityEngine;
2+
3+
#if UNITY_EDITOR
4+
using ParrelSync;
5+
#endif
6+
7+
namespace Unity.Multiplayer.Samples.BossRoom.Shared
8+
{
9+
public static class ProfileManager
10+
{
11+
public const string AuthProfileCommandLineArg = "-AuthProfile";
12+
13+
static string s_Profile;
14+
15+
public static string Profile => s_Profile ??= GetProfile();
16+
17+
static string GetProfile()
18+
{
19+
#if UNITY_EDITOR
20+
21+
//The code below makes it possible for the clone instance to log in as a different user profile in Authentication service.
22+
//This allows us to test services integration locally by utilising Parrelsync.
23+
if (ClonesManager.IsClone())
24+
{
25+
Debug.Log("This is a clone project.");
26+
var customArguments = ClonesManager.GetArgument().Split(',');
27+
28+
//second argument is our custom ID, but if it's not set we would just use some default.
29+
30+
var hardcodedProfileID = customArguments.Length > 1 ? customArguments[1] : "defaultCloneID";
31+
32+
return hardcodedProfileID;
33+
}
34+
#else
35+
var arguments = System.Environment.GetCommandLineArgs();
36+
for (int i = 0; i < arguments.Length; i++)
37+
{
38+
if (arguments[i] == AuthProfileCommandLineArg)
39+
{
40+
var profileId = arguments[i + 1];
41+
return profileId;
42+
}
43+
}
44+
#endif
45+
return "";
46+
}
47+
}
48+
}

Assets/BossRoom/Scripts/Shared/ProfileManager.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Assets/BossRoom/Scripts/Shared/com.unity.multiplayer.samples.bossroom.shared.asmdef

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
"Unity.Netcode.Adapter.UTP",
1212
"Unity.Collections",
1313
"Unity.Multiplayer.Samples.Utilities",
14-
"Unity.Networking.Transport"
14+
"Unity.Networking.Transport",
15+
"ParrelSync"
1516
],
1617
"includePlatforms": [],
1718
"excludePlatforms": [],
@@ -22,4 +23,4 @@
2223
"defineConstraints": [],
2324
"versionDefines": [],
2425
"noEngineReferences": false
25-
}
26+
}

0 commit comments

Comments
 (0)