当前提交
8cbba883
共有 127 个文件被更改,包括 6015 次插入 和 5290 次删除
-
3.gitignore
-
4Assets/Prefabs/UI/JoinContent.prefab
-
7Assets/Prefabs/UI/LobbyButtonUI.prefab
-
16Assets/Prefabs/UI/LobbyCodeCanvas.prefab
-
22Assets/Prefabs/UI/LobbyGameCanvas.prefab
-
42Assets/Prefabs/UI/LobbyUserList.prefab
-
4Assets/Prefabs/UI/PlayerInteractionPanel.prefab
-
17Assets/Prefabs/UI/RelayCodeCanvas.prefab
-
283Assets/Scenes/mainScene.unity
-
2Assets/Scripts/Auth/Identity.cs
-
2Assets/Scripts/Auth/SubIdentity_Authentication.cs
-
159Assets/Scripts/Entities/GameStateManager.cs
-
6Assets/Scripts/Entities/LobbyServiceData.cs
-
14Assets/Scripts/Entities/LobbyUser.cs
-
542Assets/Scripts/Entities/LocalLobby.cs
-
24Assets/Scripts/Tests/Editor/LobbyTests.cs
-
6Assets/Scripts/Tests/Editor/ObserverTests.cs
-
2Assets/Scripts/Tests/Editor/Tests.Editor.asmdef
-
2Assets/Scripts/Tests/PlayMode/Tests.Play.asmdef
-
3Assets/Scripts/UI/BackButtonUI.cs
-
7Assets/Scripts/UI/CountdownUI.cs
-
7Assets/Scripts/UI/CreateMenuUI.cs
-
3Assets/Scripts/UI/EmoteButtonUI.cs
-
5Assets/Scripts/UI/EndGameButtonUI.cs
-
3Assets/Scripts/UI/ExitButtonUI.cs
-
3Assets/Scripts/UI/GameStateVisibilityUI.cs
-
61Assets/Scripts/UI/JoinMenuUI.cs
-
15Assets/Scripts/UI/LobbyButtonUI.cs
-
2Assets/Scripts/UI/MainMenuUI.cs
-
2Assets/Scripts/UI/NameChangeUI.cs
-
5Assets/Scripts/UI/ObserverPanel.cs
-
3Assets/Scripts/UI/PlayerNameUI.cs
-
3Assets/Scripts/UI/ReadyCheckUI.cs
-
3Assets/Scripts/UI/SpinnerUI.cs
-
3Assets/Scripts/UI/UIPanelBase.cs
-
5Assets/Scripts/UI/UserStateVisibilityUI.cs
-
42Assets/Scripts/UI/JoinCreateLobbyUI.cs
-
4Assets/Scripts/UI/InLobbyUserUI.cs
-
2Assets/Scripts/LobbyRelaySample.asmdef
-
61README.md
-
999~Documentation/Images/dashboard1_beta.png
-
999~Documentation/Images/services1.PNG
-
999~Documentation/Images/services2.PNG
-
251~Documentation/Images/tutorial_1_lobbyList.png
-
353~Documentation/Images/tutorial_2_createMenu.png
-
565~Documentation/Images/tutorial_3_HostGame.png
-
352~Documentation/Images/tutorial_4_newLobby.png
-
947~Documentation/Images/tutorial_5_editorCow.png
-
803~Documentation/Images/tutorial_6_countDown.png
-
971~Documentation/Images/tutorial_7_ingame.png
-
200Assets/Scripts/Infrastructure/Locator.cs
-
126Assets/Scripts/Infrastructure/LogHandler.cs
-
176Assets/Scripts/Infrastructure/Messenger.cs
-
5Assets/Scripts/Auth/NameGenerator.cs
-
276Assets/Scripts/Infrastructure/UpdateSlow.cs
-
4Assets/Scripts/Entities/LocalLobbyObserver.cs
-
130Assets/Scripts/Tests/PlayMode/LobbyReadyCheckTests.cs
-
163Assets/Scripts/Tests/PlayMode/LobbyRoundtripTests.cs
-
33Assets/Scripts/UI/DisplayCodeUI.cs
-
60Assets/Scripts/UI/InLobbyUserList.cs
-
19Assets/Scripts/UI/LobbyNameUI.cs
-
19Assets/Scripts/UI/RelayAddressUI.cs
-
22Assets/Scripts/UI/ShowWhenLobbyStateUI.cs
-
15Assets/Scripts/UI/StartLobbyButtonUI.cs
-
108Assets/Scripts/Lobby/LobbyAPIInterface.cs
-
218Assets/Scripts/Lobby/LobbyAsyncRequests.cs
-
109Assets/Scripts/Lobby/LobbyContentHeartbeat.cs
-
23Assets/Scripts/Lobby/LobbyListHeartbeat.cs
-
63Assets/Scripts/Lobby/ReadyCheck.cs
-
89Assets/Scripts/Lobby/ToLocalLobby.cs
-
4Assets/Scripts/Entities/LobbyDataObserver.cs
-
67Assets/Scripts/Entities/LobbyReadyCheck.cs
-
131Assets/Scripts/Tests/PlayMode/ReadyCheckTests.cs
-
163Assets/Scripts/Tests/PlayMode/RoomsRoundtripTests.cs
-
11Assets/Scripts/UI/RelayCodeUI.cs.meta
-
5Assets/Scripts/UI/SerializedValueEvents.cs
-
11Assets/Scripts/UI/SerializedValueEvents.cs.meta
-
19Assets/Scripts/UI/LobbyStateVisibilityUI.cs
-
60Assets/Scripts/UI/LobbyUsersUI.cs
-
27Assets/Scripts/UI/RelayCodeUI.cs
-
26Assets/Scripts/UI/RoomCodeUI.cs
-
16Assets/Scripts/UI/ServerAddressUI.cs
-
16Assets/Scripts/UI/ServerNameUI.cs
-
12Assets/Scripts/UI/StartLobbyButton.cs
-
8Assets/Scripts/Utilities.meta
-
11Assets/TempDeleteAllRooms.cs.meta
-
33Assets/TempDeleteAllRooms.cs
-
167ProjectSettings/SceneTemplateSettings.json
-
16ProjectSettings/BurstAotSettings_StandaloneWindows.json
-
6ProjectSettings/CommonBurstAotSettings.json
-
0/Assets/Scripts/Entities/LocalLobbyObserver.cs.meta
-
0/Assets/Scripts/Entities/LocalLobby.cs.meta
-
0/Assets/Scripts/Entities/LocalLobby.cs
-
0/Assets/Scripts/Tests/PlayMode/LobbyRoundtripTests.cs.meta
-
0/Assets/Scripts/Tests/PlayMode/LobbyReadyCheckTests.cs.meta
-
0/Assets/Scripts/UI/StartLobbyButtonUI.cs.meta
-
0/Assets/Scripts/UI/ShowWhenLobbyStateUI.cs.meta
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
[Flags] |
|||
public enum LobbyState |
|||
{ |
|||
Lobby = 1, |
|||
CountDown = 2, |
|||
InGame = 4 |
|||
} |
|||
|
|||
public struct LobbyInfo |
|||
{ |
|||
public string RoomID { get; set; } |
|||
public string RoomCode { get; set; } |
|||
public string RelayCode { get; set; } |
|||
public string LobbyName { get; set; } |
|||
public bool Private { get; set; } |
|||
public int MaxPlayerCount { get; set; } |
|||
public LobbyState State { get; set; } |
|||
public long? AllPlayersReadyTime { get; set; } |
|||
|
|||
public LobbyInfo(LobbyInfo existing) |
|||
{ |
|||
RoomID = existing.RoomID; |
|||
RoomCode = existing.RoomCode; |
|||
RelayCode = existing.RelayCode; |
|||
LobbyName = existing.LobbyName; |
|||
Private = existing.Private; |
|||
MaxPlayerCount = existing.MaxPlayerCount; |
|||
State = existing.State; |
|||
AllPlayersReadyTime = existing.AllPlayersReadyTime; |
|||
} |
|||
|
|||
public LobbyInfo(string roomCode) |
|||
{ |
|||
RoomID = null; |
|||
RoomCode = roomCode; |
|||
RelayCode = null; |
|||
LobbyName = null; |
|||
Private = false; |
|||
MaxPlayerCount = -1; |
|||
State = LobbyState.Lobby; |
|||
AllPlayersReadyTime = null; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// The local lobby data that the game can observe
|
|||
/// </summary>
|
|||
[System.Serializable] |
|||
public class LobbyData : Observed<LobbyData> |
|||
{ |
|||
Dictionary<string, LobbyUser> m_LobbyUsers = new Dictionary<string, LobbyUser>(); |
|||
public Dictionary<string, LobbyUser> LobbyUsers => m_LobbyUsers; |
|||
|
|||
#region LocalLobbyData
|
|||
private LobbyInfo m_data; |
|||
public LobbyInfo Data |
|||
{ |
|||
get { return new LobbyInfo(m_data); } |
|||
} |
|||
|
|||
float m_CountDownTime; |
|||
|
|||
public float CountDownTime |
|||
{ |
|||
get { return m_CountDownTime; } |
|||
set |
|||
{ |
|||
m_CountDownTime = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
DateTime m_TargetEndTime; |
|||
|
|||
public DateTime TargetEndTime |
|||
{ |
|||
get => m_TargetEndTime; |
|||
set |
|||
{ |
|||
m_TargetEndTime = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
ServerAddress m_relayServer; |
|||
|
|||
public ServerAddress RelayServer |
|||
{ |
|||
get => m_relayServer; |
|||
set |
|||
{ |
|||
m_relayServer = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
#endregion
|
|||
|
|||
public void AddPlayer(LobbyUser user) |
|||
{ |
|||
if (m_LobbyUsers.ContainsKey(user.ID)) |
|||
{ |
|||
Debug.LogError($"Cant add player {user.DisplayName}({user.ID}) to room: {RoomID} twice"); |
|||
return; |
|||
} |
|||
|
|||
DoAddPlayer(user); |
|||
OnChanged(this); |
|||
} |
|||
|
|||
private void DoAddPlayer(LobbyUser user) |
|||
{ |
|||
m_LobbyUsers.Add(user.ID, user); |
|||
user.onChanged += OnChangedUser; |
|||
} |
|||
|
|||
public void RemovePlayer(LobbyUser user) |
|||
{ |
|||
DoRemoveUser(user); |
|||
OnChanged(this); |
|||
} |
|||
|
|||
private void DoRemoveUser(LobbyUser user) |
|||
{ |
|||
if (!m_LobbyUsers.ContainsKey(user.ID)) |
|||
{ |
|||
Debug.LogWarning($"Player {user.DisplayName}({user.ID}) does not exist in room: {RoomID}"); |
|||
return; |
|||
} |
|||
|
|||
m_LobbyUsers.Remove(user.ID); |
|||
user.onChanged -= OnChangedUser; |
|||
} |
|||
|
|||
private void OnChangedUser(LobbyUser user) |
|||
{ |
|||
OnChanged(this); |
|||
} |
|||
|
|||
public string RoomID |
|||
{ |
|||
get => m_data.RoomID; |
|||
set |
|||
{ |
|||
m_data.RoomID = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public string RoomCode |
|||
{ |
|||
get => m_data.RoomCode; |
|||
set |
|||
{ |
|||
m_data.RoomCode = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public string RelayCode |
|||
{ |
|||
get => m_data.RelayCode; |
|||
set |
|||
{ |
|||
m_data.RelayCode = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public string LobbyName |
|||
{ |
|||
get => m_data.LobbyName; |
|||
set |
|||
{ |
|||
m_data.LobbyName = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public LobbyState State |
|||
{ |
|||
get => m_data.State; |
|||
set |
|||
{ |
|||
m_data.State = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public bool Private |
|||
{ |
|||
get => m_data.Private; |
|||
set |
|||
{ |
|||
m_data.Private = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public int PlayerCount => m_LobbyUsers.Count; |
|||
|
|||
public int MaxPlayerCount |
|||
{ |
|||
get => m_data.MaxPlayerCount; |
|||
set |
|||
{ |
|||
m_data.MaxPlayerCount = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public long? AllPlayersReadyTime => m_data.AllPlayersReadyTime; |
|||
|
|||
/// <summary>
|
|||
/// Checks if we have n players that have the Status.
|
|||
/// -1 Count means you need all Lobbyusers
|
|||
/// </summary>
|
|||
/// <returns>True if enough players are of the input status.</returns>
|
|||
public bool PlayersOfState(UserStatus status, int playersCount = -1) |
|||
{ |
|||
var statePlayers = m_LobbyUsers.Values.Count(user => user.UserStatus == status); |
|||
|
|||
if (playersCount < 0) |
|||
return statePlayers == m_LobbyUsers.Count; |
|||
return statePlayers == playersCount; |
|||
} |
|||
|
|||
public void CopyObserved(LobbyInfo info, Dictionary<string, LobbyUser> oldUsers) |
|||
{ |
|||
m_data = info; |
|||
if (oldUsers == null) |
|||
m_LobbyUsers = new Dictionary<string, LobbyUser>(); |
|||
else |
|||
{ |
|||
List<LobbyUser> toRemove = new List<LobbyUser>(); |
|||
foreach (var user in m_LobbyUsers) |
|||
{ |
|||
if (oldUsers.ContainsKey(user.Key)) |
|||
user.Value.CopyObserved(oldUsers[user.Key]); |
|||
else |
|||
toRemove.Add(user.Value); |
|||
} |
|||
|
|||
foreach (var remove in toRemove) |
|||
{ |
|||
DoRemoveUser(remove); |
|||
} |
|||
|
|||
foreach (var oldUser in oldUsers) |
|||
{ |
|||
if (!m_LobbyUsers.ContainsKey(oldUser.Key)) |
|||
DoAddPlayer(oldUser.Value); |
|||
} |
|||
} |
|||
|
|||
OnChanged(this); |
|||
} |
|||
|
|||
public override void CopyObserved(LobbyData oldObserved) |
|||
{ |
|||
CopyObserved(oldObserved.Data, oldObserved.m_LobbyUsers); |
|||
} |
|||
} |
|||
} |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
[Flags] |
|||
public enum LobbyState |
|||
{ |
|||
Lobby = 1, |
|||
CountDown = 2, |
|||
InGame = 4 |
|||
} |
|||
|
|||
public struct LobbyInfo |
|||
{ |
|||
public string LobbyID { get; set; } |
|||
public string LobbyCode { get; set; } |
|||
public string RelayCode { get; set; } |
|||
public string LobbyName { get; set; } |
|||
public bool Private { get; set; } |
|||
public int MaxPlayerCount { get; set; } |
|||
public LobbyState State { get; set; } |
|||
public long? AllPlayersReadyTime { get; set; } |
|||
|
|||
public LobbyInfo(LobbyInfo existing) |
|||
{ |
|||
LobbyID = existing.LobbyID; |
|||
LobbyCode = existing.LobbyCode; |
|||
RelayCode = existing.RelayCode; |
|||
LobbyName = existing.LobbyName; |
|||
Private = existing.Private; |
|||
MaxPlayerCount = existing.MaxPlayerCount; |
|||
State = existing.State; |
|||
AllPlayersReadyTime = existing.AllPlayersReadyTime; |
|||
} |
|||
|
|||
public LobbyInfo(string lobbyCode) |
|||
{ |
|||
LobbyID = null; |
|||
LobbyCode = lobbyCode; |
|||
RelayCode = null; |
|||
LobbyName = null; |
|||
Private = false; |
|||
MaxPlayerCount = -1; |
|||
State = LobbyState.Lobby; |
|||
AllPlayersReadyTime = null; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// A local wrapper around a lobby's remote data, with additional functionality for providing that data to UI elements and tracking local player objects.
|
|||
/// </summary>
|
|||
[System.Serializable] |
|||
public class LocalLobby : Observed<LocalLobby> |
|||
{ |
|||
Dictionary<string, LobbyUser> m_LobbyUsers = new Dictionary<string, LobbyUser>(); |
|||
public Dictionary<string, LobbyUser> LobbyUsers => m_LobbyUsers; |
|||
|
|||
#region LocalLobbyData
|
|||
private LobbyInfo m_data; |
|||
public LobbyInfo Data |
|||
{ |
|||
get { return new LobbyInfo(m_data); } |
|||
} |
|||
|
|||
float m_CountDownTime; |
|||
|
|||
public float CountDownTime |
|||
{ |
|||
get { return m_CountDownTime; } |
|||
set |
|||
{ |
|||
m_CountDownTime = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
DateTime m_TargetEndTime; |
|||
|
|||
public DateTime TargetEndTime |
|||
{ |
|||
get => m_TargetEndTime; |
|||
set |
|||
{ |
|||
m_TargetEndTime = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
ServerAddress m_relayServer; |
|||
|
|||
public ServerAddress RelayServer |
|||
{ |
|||
get => m_relayServer; |
|||
set |
|||
{ |
|||
m_relayServer = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
#endregion
|
|||
|
|||
public void AddPlayer(LobbyUser user) |
|||
{ |
|||
if (m_LobbyUsers.ContainsKey(user.ID)) |
|||
{ |
|||
Debug.LogError($"Cant add player {user.DisplayName}({user.ID}) to lobby: {LobbyID} twice"); |
|||
return; |
|||
} |
|||
|
|||
DoAddPlayer(user); |
|||
OnChanged(this); |
|||
} |
|||
|
|||
private void DoAddPlayer(LobbyUser user) |
|||
{ |
|||
m_LobbyUsers.Add(user.ID, user); |
|||
user.onChanged += OnChangedUser; |
|||
} |
|||
|
|||
public void RemovePlayer(LobbyUser user) |
|||
{ |
|||
DoRemoveUser(user); |
|||
OnChanged(this); |
|||
} |
|||
|
|||
private void DoRemoveUser(LobbyUser user) |
|||
{ |
|||
if (!m_LobbyUsers.ContainsKey(user.ID)) |
|||
{ |
|||
Debug.LogWarning($"Player {user.DisplayName}({user.ID}) does not exist in lobby: {LobbyID}"); |
|||
return; |
|||
} |
|||
|
|||
m_LobbyUsers.Remove(user.ID); |
|||
user.onChanged -= OnChangedUser; |
|||
} |
|||
|
|||
private void OnChangedUser(LobbyUser user) |
|||
{ |
|||
OnChanged(this); |
|||
} |
|||
|
|||
public string LobbyID |
|||
{ |
|||
get => m_data.LobbyID; |
|||
set |
|||
{ |
|||
m_data.LobbyID = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public string LobbyCode |
|||
{ |
|||
get => m_data.LobbyCode; |
|||
set |
|||
{ |
|||
m_data.LobbyCode = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public string RelayCode |
|||
{ |
|||
get => m_data.RelayCode; |
|||
set |
|||
{ |
|||
m_data.RelayCode = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public string LobbyName |
|||
{ |
|||
get => m_data.LobbyName; |
|||
set |
|||
{ |
|||
m_data.LobbyName = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public LobbyState State |
|||
{ |
|||
get => m_data.State; |
|||
set |
|||
{ |
|||
m_data.State = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public bool Private |
|||
{ |
|||
get => m_data.Private; |
|||
set |
|||
{ |
|||
m_data.Private = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public int PlayerCount => m_LobbyUsers.Count; |
|||
|
|||
public int MaxPlayerCount |
|||
{ |
|||
get => m_data.MaxPlayerCount; |
|||
set |
|||
{ |
|||
m_data.MaxPlayerCount = value; |
|||
OnChanged(this); |
|||
} |
|||
} |
|||
|
|||
public long? AllPlayersReadyTime => m_data.AllPlayersReadyTime; |
|||
|
|||
/// <summary>
|
|||
/// Checks if we have n players that have the Status.
|
|||
/// -1 Count means you need all Lobbyusers
|
|||
/// </summary>
|
|||
/// <returns>True if enough players are of the input status.</returns>
|
|||
public bool PlayersOfState(UserStatus status, int playersCount = -1) |
|||
{ |
|||
var statePlayers = m_LobbyUsers.Values.Count(user => user.UserStatus == status); |
|||
|
|||
if (playersCount < 0) |
|||
return statePlayers == m_LobbyUsers.Count; |
|||
return statePlayers == playersCount; |
|||
} |
|||
|
|||
public void CopyObserved(LobbyInfo info, Dictionary<string, LobbyUser> oldUsers) |
|||
{ |
|||
m_data = info; |
|||
if (oldUsers == null) |
|||
m_LobbyUsers = new Dictionary<string, LobbyUser>(); |
|||
else |
|||
{ |
|||
List<LobbyUser> toRemove = new List<LobbyUser>(); |
|||
foreach (var user in m_LobbyUsers) |
|||
{ |
|||
if (oldUsers.ContainsKey(user.Key)) |
|||
user.Value.CopyObserved(oldUsers[user.Key]); |
|||
else |
|||
toRemove.Add(user.Value); |
|||
} |
|||
|
|||
foreach (var remove in toRemove) |
|||
{ |
|||
DoRemoveUser(remove); |
|||
} |
|||
|
|||
foreach (var oldUser in oldUsers) |
|||
{ |
|||
if (!m_LobbyUsers.ContainsKey(oldUser.Key)) |
|||
DoAddPlayer(oldUser.Value); |
|||
} |
|||
} |
|||
|
|||
OnChanged(this); |
|||
} |
|||
|
|||
public override void CopyObserved(LocalLobby oldObserved) |
|||
{ |
|||
CopyObserved(oldObserved.Data, oldObserved.m_LobbyUsers); |
|||
} |
|||
} |
|||
} |
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Observer UI panel base class, for UI panels that need hiding, and hookup to observerBehaviours
|
|||
/// Observer UI panel base class. This allows UI elements to be shown or hidden based on an Observed element.
|
|||
/// <typeparam name="T"></typeparam>
|
|||
|
|||
|
|||
} |
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// The panel that holds the room joining and creation panels.
|
|||
/// </summary>
|
|||
public class JoinCreateRoomUI : ObserverPanel<LocalGameState> |
|||
{ |
|||
public override void ObservedUpdated(LocalGameState observed) |
|||
{ |
|||
if (observed.State == GameState.JoinMenu) |
|||
{ |
|||
Show(); |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.QueryRooms, null); |
|||
} |
|||
else |
|||
{ |
|||
Hide(); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// The panel that holds the lobby joining and creation panels.
|
|||
/// </summary>
|
|||
public class JoinCreateLobbyUI : ObserverPanel<LocalGameState> |
|||
{ |
|||
public override void ObservedUpdated(LocalGameState observed) |
|||
{ |
|||
if (observed.State == GameState.JoinMenu) |
|||
{ |
|||
Show(); |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.QueryLobbies, null); |
|||
} |
|||
else |
|||
{ |
|||
Hide(); |
|||
} |
|||
} |
|||
} |
|||
} |
999
~Documentation/Images/dashboard1_beta.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
999
~Documentation/Images/services1.PNG
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
999
~Documentation/Images/services2.PNG
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
251
~Documentation/Images/tutorial_1_lobbyList.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
353
~Documentation/Images/tutorial_2_createMenu.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
565
~Documentation/Images/tutorial_3_HostGame.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
352
~Documentation/Images/tutorial_4_newLobby.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
947
~Documentation/Images/tutorial_5_editorCow.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
971
~Documentation/Images/tutorial_7_ingame.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
|
|||
using LobbyRelaySample.Auth; |
|||
using System; |
|||
using System.Collections.Generic; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Allows Located services to transfer data to their replacements if needed.
|
|||
/// </summary>
|
|||
/// <typeparam name="T">The base interface type you want to Provide.</typeparam>
|
|||
public interface IProvidable<T> |
|||
{ |
|||
void OnReProvided(T previousProvider); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Base Locator behavior, without static access.
|
|||
/// </summary>
|
|||
public class LocatorBase |
|||
{ |
|||
private Dictionary<Type, object> m_provided = new Dictionary<Type, object>(); |
|||
|
|||
/// <summary>
|
|||
/// On construction, we can prepare default implementations of any services we expect to be required. This way, if for some reason the actual implementations
|
|||
/// are never Provided (e.g. for tests), nothing will break.
|
|||
/// </summary>
|
|||
public LocatorBase() |
|||
{ |
|||
Provide(new Messenger()); |
|||
Provide(new UpdateSlowNoop()); |
|||
Provide(new IdentityNoop()); |
|||
|
|||
FinishConstruction(); |
|||
} |
|||
|
|||
protected virtual void FinishConstruction() { } |
|||
|
|||
/// <summary>
|
|||
/// Call this to indicate that something is available for global access.
|
|||
/// </summary>
|
|||
private void ProvideAny<T>(T instance) where T : IProvidable<T> |
|||
{ |
|||
Type type = typeof(T); |
|||
if (m_provided.ContainsKey(type)) |
|||
{ |
|||
var previousProvision = (T)m_provided[type]; |
|||
instance.OnReProvided(previousProvision); |
|||
m_provided.Remove(type); |
|||
} |
|||
|
|||
m_provided.Add(type, instance); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// If a T has previously been Provided, this will retrieve it. Else, null is returned.
|
|||
/// </summary>
|
|||
private T Locate<T>() where T : class |
|||
{ |
|||
Type type = typeof(T); |
|||
if (!m_provided.ContainsKey(type)) |
|||
return null; |
|||
return m_provided[type] as T; |
|||
} |
|||
|
|||
// To limit global access to only components that should have it, and to reduce programmer error, we'll declare explicit flavors of Provide and getters for them.
|
|||
public IMessenger Messenger => Locate<IMessenger>(); |
|||
public void Provide(IMessenger messenger) { ProvideAny(messenger); } |
|||
|
|||
public IUpdateSlow UpdateSlow => Locate<IUpdateSlow>(); |
|||
public void Provide(IUpdateSlow updateSlow) { ProvideAny(updateSlow); } |
|||
|
|||
public IIdentity Identity => Locate<IIdentity>(); |
|||
public void Provide(IIdentity identity) { ProvideAny(identity); } |
|||
|
|||
// As you add more Provided types, be sure their default implementations are included in the constructor.
|
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Anything which provides itself to a Locator can then be globally accessed. This should be a single access point for things that *want* to be singleton (that is,
|
|||
/// when they want to be available for use by arbitrary, unknown clients) but might not always be available or might need alternate flavors for tests, logging, etc.
|
|||
/// </summary>
|
|||
public class Locator : LocatorBase |
|||
{ |
|||
private static Locator s_instance; |
|||
|
|||
public static Locator Get |
|||
{ |
|||
get |
|||
{ |
|||
if (s_instance == null) |
|||
s_instance = new Locator(); |
|||
return s_instance; |
|||
} |
|||
} |
|||
|
|||
protected override void FinishConstruction() |
|||
{ |
|||
s_instance = this; |
|||
} |
|||
} |
|||
using LobbyRelaySample.Auth; |
|||
using System; |
|||
using System.Collections.Generic; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Allows Located services to transfer data to their replacements if needed.
|
|||
/// </summary>
|
|||
/// <typeparam name="T">The base interface type you want to Provide.</typeparam>
|
|||
public interface IProvidable<T> |
|||
{ |
|||
void OnReProvided(T previousProvider); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Base Locator behavior, without static access.
|
|||
/// </summary>
|
|||
public class LocatorBase |
|||
{ |
|||
private Dictionary<Type, object> m_provided = new Dictionary<Type, object>(); |
|||
|
|||
/// <summary>
|
|||
/// On construction, we can prepare default implementations of any services we expect to be required. This way, if for some reason the actual implementations
|
|||
/// are never Provided (e.g. for tests), nothing will break.
|
|||
/// </summary>
|
|||
public LocatorBase() |
|||
{ |
|||
Provide(new Messenger()); |
|||
Provide(new UpdateSlowNoop()); |
|||
Provide(new IdentityNoop()); |
|||
|
|||
FinishConstruction(); |
|||
} |
|||
|
|||
protected virtual void FinishConstruction() { } |
|||
|
|||
/// <summary>
|
|||
/// Call this to indicate that something is available for global access.
|
|||
/// </summary>
|
|||
private void ProvideAny<T>(T instance) where T : IProvidable<T> |
|||
{ |
|||
Type type = typeof(T); |
|||
if (m_provided.ContainsKey(type)) |
|||
{ |
|||
var previousProvision = (T)m_provided[type]; |
|||
instance.OnReProvided(previousProvision); |
|||
m_provided.Remove(type); |
|||
} |
|||
|
|||
m_provided.Add(type, instance); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// If a T has previously been Provided, this will retrieve it. Else, null is returned.
|
|||
/// </summary>
|
|||
private T Locate<T>() where T : class |
|||
{ |
|||
Type type = typeof(T); |
|||
if (!m_provided.ContainsKey(type)) |
|||
return null; |
|||
return m_provided[type] as T; |
|||
} |
|||
|
|||
// To limit global access to only components that should have it, and to reduce programmer error, we'll declare explicit flavors of Provide and getters for them.
|
|||
public IMessenger Messenger => Locate<IMessenger>(); |
|||
public void Provide(IMessenger messenger) { ProvideAny(messenger); } |
|||
|
|||
public IUpdateSlow UpdateSlow => Locate<IUpdateSlow>(); |
|||
public void Provide(IUpdateSlow updateSlow) { ProvideAny(updateSlow); } |
|||
|
|||
public IIdentity Identity => Locate<IIdentity>(); |
|||
public void Provide(IIdentity identity) { ProvideAny(identity); } |
|||
|
|||
// As you add more Provided types, be sure their default implementations are included in the constructor.
|
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Anything which provides itself to a Locator can then be globally accessed. This should be a single access point for things that *want* to be singleton (that is,
|
|||
/// when they want to be available for use by arbitrary, unknown clients) but might not always be available or might need alternate flavors for tests, logging, etc.
|
|||
/// </summary>
|
|||
public class Locator : LocatorBase |
|||
{ |
|||
private static Locator s_instance; |
|||
|
|||
public static Locator Get |
|||
{ |
|||
get |
|||
{ |
|||
if (s_instance == null) |
|||
s_instance = new Locator(); |
|||
return s_instance; |
|||
} |
|||
} |
|||
|
|||
protected override void FinishConstruction() |
|||
{ |
|||
s_instance = this; |
|||
} |
|||
} |
|||
} |
|
|||
using System; |
|||
using UnityEngine; |
|||
using Object = UnityEngine.Object; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
public enum LogMode |
|||
{ |
|||
Critical, // Errors only.
|
|||
Warnings, // Errors and Warnings
|
|||
Verbose // Everything
|
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Overrides the Default Unity Logging with our own
|
|||
/// </summary>
|
|||
public class LogHandler : ILogHandler |
|||
{ |
|||
public LogMode mode = LogMode.Critical; |
|||
|
|||
static LogHandler s_instance; |
|||
ILogHandler m_DefaultLogHandler = Debug.unityLogger.logHandler; //Store the unity default logger to print to console.
|
|||
|
|||
public static LogHandler Get() |
|||
{ |
|||
if (s_instance != null) return s_instance; |
|||
s_instance = new LogHandler(); |
|||
Debug.unityLogger.logHandler = s_instance; |
|||
return s_instance; |
|||
} |
|||
|
|||
public void LogFormat(LogType logType, Object context, string format, params object[] args) |
|||
{ |
|||
if (logType == LogType.Exception) // Exceptions are captured by LogException?
|
|||
return; |
|||
|
|||
if (logType == LogType.Error || logType == LogType.Assert) |
|||
{ |
|||
m_DefaultLogHandler.LogFormat(logType, context, format, args); |
|||
return; |
|||
} |
|||
|
|||
if (mode == LogMode.Critical) |
|||
return; |
|||
|
|||
if (logType == LogType.Warning) |
|||
{ |
|||
m_DefaultLogHandler.LogFormat(logType, context, format, args); |
|||
return; |
|||
} |
|||
|
|||
if (mode != LogMode.Verbose) |
|||
return; |
|||
|
|||
m_DefaultLogHandler.LogFormat(logType, context, format, args); |
|||
} |
|||
|
|||
public void LogException(Exception exception, Object context) |
|||
{ |
|||
m_DefaultLogHandler.LogException(exception, context); |
|||
} |
|||
} |
|||
} |
|||
using System; |
|||
using UnityEngine; |
|||
using Object = UnityEngine.Object; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
public enum LogMode |
|||
{ |
|||
Critical, // Errors only.
|
|||
Warnings, // Errors and Warnings
|
|||
Verbose // Everything
|
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Overrides the Default Unity Logging with our own
|
|||
/// </summary>
|
|||
public class LogHandler : ILogHandler |
|||
{ |
|||
public LogMode mode = LogMode.Critical; |
|||
|
|||
static LogHandler s_instance; |
|||
ILogHandler m_DefaultLogHandler = Debug.unityLogger.logHandler; //Store the unity default logger to print to console.
|
|||
|
|||
public static LogHandler Get() |
|||
{ |
|||
if (s_instance != null) return s_instance; |
|||
s_instance = new LogHandler(); |
|||
Debug.unityLogger.logHandler = s_instance; |
|||
return s_instance; |
|||
} |
|||
|
|||
public void LogFormat(LogType logType, Object context, string format, params object[] args) |
|||
{ |
|||
if (logType == LogType.Exception) // Exceptions are captured by LogException?
|
|||
return; |
|||
|
|||
if (logType == LogType.Error || logType == LogType.Assert) |
|||
{ |
|||
m_DefaultLogHandler.LogFormat(logType, context, format, args); |
|||
return; |
|||
} |
|||
|
|||
if (mode == LogMode.Critical) |
|||
return; |
|||
|
|||
if (logType == LogType.Warning) |
|||
{ |
|||
m_DefaultLogHandler.LogFormat(logType, context, format, args); |
|||
return; |
|||
} |
|||
|
|||
if (mode != LogMode.Verbose) |
|||
return; |
|||
|
|||
m_DefaultLogHandler.LogFormat(logType, context, format, args); |
|||
} |
|||
|
|||
public void LogException(Exception exception, Object context) |
|||
{ |
|||
m_DefaultLogHandler.LogException(exception, context); |
|||
} |
|||
} |
|||
} |
|
|||
using System.Collections.Generic; |
|||
using UnityEngine; |
|||
using Stopwatch = System.Diagnostics.Stopwatch; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Ensure that message contents are obvious but not dependent on spelling strings correctly.
|
|||
/// </summary>
|
|||
public enum MessageType |
|||
{ |
|||
// These are assigned arbitrary explicit values so that if a MessageType is serialized and more enum values are later inserted/removed, the serialized values need not be reassigned.
|
|||
// (If you want to remove a message, make sure it isn't serialized somewhere first.)
|
|||
None = 0, |
|||
RenameRequest = 1, |
|||
JoinRoomRequest = 2, |
|||
CreateRoomRequest = 3, |
|||
QueryRooms = 4, |
|||
PlayerJoinedRoom = 5, |
|||
PlayerLeftRoom = 6, |
|||
ChangeGameState = 7, |
|||
ChangeLobbyUserState = 8, |
|||
HostInitReadyCheck = 9, |
|||
LocalUserReadyCheckResponse = 10, |
|||
UserSetEmote = 11, |
|||
ToLobby = 12, |
|||
Client_EndReadyCountdownAt = 13, |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Something that wants to subscribe to messages from arbitrary, unknown senders.
|
|||
/// </summary>
|
|||
public interface IReceiveMessages |
|||
{ |
|||
void OnReceiveMessage(MessageType type, object msg); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Something to which IReceiveMessages can send/subscribe for arbitrary messages.
|
|||
/// </summary>
|
|||
public interface IMessenger : IReceiveMessages, IProvidable<IMessenger> |
|||
{ |
|||
void Subscribe(IReceiveMessages receiver); |
|||
void Unsubscribe(IReceiveMessages receiver); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Core mechanism for routing messages to arbitrary listeners.
|
|||
/// </summary>
|
|||
public class Messenger : IMessenger |
|||
{ |
|||
private List<IReceiveMessages> m_receivers = new List<IReceiveMessages>(); |
|||
private const float k_durationToleranceMs = 10; |
|||
|
|||
/// <summary>
|
|||
/// Assume that you won't receive messages in a specific order.
|
|||
/// </summary>
|
|||
public virtual void Subscribe(IReceiveMessages receiver) |
|||
{ |
|||
if (!m_receivers.Contains(receiver)) |
|||
m_receivers.Add(receiver); |
|||
} |
|||
|
|||
public virtual void Unsubscribe(IReceiveMessages receiver) |
|||
{ |
|||
m_receivers.Remove(receiver); |
|||
} |
|||
|
|||
public virtual void OnReceiveMessage(MessageType type, object msg) |
|||
{ |
|||
Stopwatch stopwatch = new Stopwatch(); |
|||
for (int r = 0; r < m_receivers.Count; r++) |
|||
{ |
|||
stopwatch.Restart(); |
|||
m_receivers[r].OnReceiveMessage(type, msg); |
|||
stopwatch.Stop(); |
|||
if (stopwatch.ElapsedMilliseconds > k_durationToleranceMs) |
|||
Debug.LogWarning($"Message recipient \"{m_receivers[r]}\" took too long to process message \"{msg}\" of type {type}"); |
|||
} |
|||
} |
|||
|
|||
public void OnReProvided(IMessenger previousProvider) |
|||
{ |
|||
if (previousProvider is Messenger) |
|||
m_receivers.AddRange((previousProvider as Messenger).m_receivers); |
|||
} |
|||
} |
|||
} |
|||
using System.Collections.Generic; |
|||
using UnityEngine; |
|||
using Stopwatch = System.Diagnostics.Stopwatch; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Ensure that message contents are obvious but not dependent on spelling strings correctly.
|
|||
/// </summary>
|
|||
public enum MessageType |
|||
{ |
|||
// These are assigned arbitrary explicit values so that if a MessageType is serialized and more enum values are later inserted/removed, the serialized values need not be reassigned.
|
|||
// (If you want to remove a message, make sure it isn't serialized somewhere first.)
|
|||
None = 0, |
|||
RenameRequest = 1, |
|||
JoinLobbyRequest = 2, |
|||
CreateLobbyRequest = 3, |
|||
QueryLobbies = 4, |
|||
PlayerJoinedLobby = 5, |
|||
PlayerLeftLobby = 6, |
|||
ChangeGameState = 7, |
|||
ChangeLobbyUserState = 8, |
|||
HostInitReadyCheck = 9, |
|||
LocalUserReadyCheckResponse = 10, |
|||
UserSetEmote = 11, |
|||
ToLobby = 12, |
|||
Client_EndReadyCountdownAt = 13, |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Something that wants to subscribe to messages from arbitrary, unknown senders.
|
|||
/// </summary>
|
|||
public interface IReceiveMessages |
|||
{ |
|||
void OnReceiveMessage(MessageType type, object msg); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Something to which IReceiveMessages can send/subscribe for arbitrary messages.
|
|||
/// </summary>
|
|||
public interface IMessenger : IReceiveMessages, IProvidable<IMessenger> |
|||
{ |
|||
void Subscribe(IReceiveMessages receiver); |
|||
void Unsubscribe(IReceiveMessages receiver); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Core mechanism for routing messages to arbitrary listeners.
|
|||
/// </summary>
|
|||
public class Messenger : IMessenger |
|||
{ |
|||
private List<IReceiveMessages> m_receivers = new List<IReceiveMessages>(); |
|||
private const float k_durationToleranceMs = 10; |
|||
|
|||
/// <summary>
|
|||
/// Assume that you won't receive messages in a specific order.
|
|||
/// </summary>
|
|||
public virtual void Subscribe(IReceiveMessages receiver) |
|||
{ |
|||
if (!m_receivers.Contains(receiver)) |
|||
m_receivers.Add(receiver); |
|||
} |
|||
|
|||
public virtual void Unsubscribe(IReceiveMessages receiver) |
|||
{ |
|||
m_receivers.Remove(receiver); |
|||
} |
|||
|
|||
public virtual void OnReceiveMessage(MessageType type, object msg) |
|||
{ |
|||
Stopwatch stopwatch = new Stopwatch(); |
|||
for (int r = 0; r < m_receivers.Count; r++) |
|||
{ |
|||
stopwatch.Restart(); |
|||
m_receivers[r].OnReceiveMessage(type, msg); |
|||
stopwatch.Stop(); |
|||
if (stopwatch.ElapsedMilliseconds > k_durationToleranceMs) |
|||
Debug.LogWarning($"Message recipient \"{m_receivers[r]}\" took too long to process message \"{msg}\" of type {type}"); |
|||
} |
|||
} |
|||
|
|||
public void OnReProvided(IMessenger previousProvider) |
|||
{ |
|||
if (previousProvider is Messenger) |
|||
m_receivers.AddRange((previousProvider as Messenger).m_receivers); |
|||
} |
|||
} |
|||
} |
|
|||
using System.Collections.Generic; |
|||
using UnityEngine; |
|||
using Stopwatch = System.Diagnostics.Stopwatch; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
public delegate void UpdateMethod(float dt); |
|||
|
|||
public interface IUpdateSlow : IProvidable<IUpdateSlow> |
|||
{ |
|||
void OnUpdate(float dt); |
|||
void Subscribe(UpdateMethod onUpdate); |
|||
void Unsubscribe(UpdateMethod onUpdate); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// A default implementation.
|
|||
/// </summary>
|
|||
public class UpdateSlowNoop : IUpdateSlow |
|||
{ |
|||
public void OnUpdate(float dt) { } |
|||
public void Subscribe(UpdateMethod onUpdate) { } |
|||
public void Unsubscribe(UpdateMethod onUpdate) { } |
|||
public void OnReProvided(IUpdateSlow prev) { } |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Some objects might need to be on a slower update loop than the usual MonoBehaviour Update, e.g. to refresh data from services.
|
|||
/// Some might also not want to be coupled to a Unity object at all but still need an update loop.
|
|||
/// </summary>
|
|||
public class UpdateSlow : MonoBehaviour, IUpdateSlow |
|||
{ |
|||
[SerializeField] |
|||
[Tooltip("Update interval. Note that room Get requests must occur at least 1 second apart, so this period should likely be greater than that.")] |
|||
private float m_updatePeriod = 1.5f; |
|||
[SerializeField] |
|||
[Tooltip("If a subscriber to slow update takes longer than this to execute, it can be automatically unsubscribed.")] |
|||
private float m_durationToleranceMs = 10; |
|||
[SerializeField] |
|||
[Tooltip("We ordinarily automatically remove a subscriber that takes too long. Otherwise, we'll simply log.")] |
|||
private bool m_doNotRemoveIfTooLong = false; |
|||
private List<UpdateMethod> m_subscribers = new List<UpdateMethod>(); |
|||
private float m_updateTimer = 0; |
|||
private int m_nextActiveSubIndex = 0; // For staggering subscribers, to prevent spikes of lots of things triggering at once.
|
|||
|
|||
public void Awake() |
|||
{ |
|||
Locator.Get.Provide(this); |
|||
} |
|||
public void OnDestroy() |
|||
{ |
|||
// We should clean up references in case they would prevent garbage collection.
|
|||
m_subscribers.Clear(); |
|||
} |
|||
|
|||
/// <summary>Don't assume that onUpdate will be called in any particular order compared to other subscribers.</summary>
|
|||
public void Subscribe(UpdateMethod onUpdate) |
|||
{ |
|||
if (!m_subscribers.Contains(onUpdate)) |
|||
m_subscribers.Add(onUpdate); |
|||
} |
|||
/// <summary>Safe to call even if onUpdate was not previously Subscribed.</summary>
|
|||
public void Unsubscribe(UpdateMethod onUpdate) |
|||
{ |
|||
int index = m_subscribers.IndexOf(onUpdate); |
|||
if (index >= 0) |
|||
{ |
|||
m_subscribers.Remove(onUpdate); |
|||
if (index < m_nextActiveSubIndex) |
|||
m_nextActiveSubIndex--; |
|||
} |
|||
} |
|||
|
|||
private void Update() |
|||
{ |
|||
if (m_subscribers.Count == 0) |
|||
return; |
|||
m_updateTimer += Time.deltaTime; |
|||
float effectivePeriod = m_updatePeriod / m_subscribers.Count; |
|||
while (m_updateTimer > effectivePeriod) |
|||
{ |
|||
m_updateTimer -= effectivePeriod; |
|||
OnUpdate(effectivePeriod); |
|||
} |
|||
} |
|||
|
|||
public void OnUpdate(float dt) |
|||
{ |
|||
Stopwatch stopwatch = new Stopwatch(); |
|||
m_nextActiveSubIndex = System.Math.Max(0, System.Math.Min(m_subscribers.Count - 1, m_nextActiveSubIndex)); // Just a backup.
|
|||
UpdateMethod onUpdate = m_subscribers[m_nextActiveSubIndex]; |
|||
if (onUpdate == null || onUpdate.Target == null) // In case something forgets to Unsubscribe when it dies.
|
|||
{ Remove(m_nextActiveSubIndex, $"Did not Unsubscribe from UpdateSlow: {onUpdate.Target} : {onUpdate.Method}"); |
|||
return; |
|||
} |
|||
if (onUpdate.Method.ToString().Contains("<")) // Detect an anonymous or lambda or local method that cannot be Unsubscribed, by checking for a character that can't exist in a declared method name.
|
|||
{ Remove(m_nextActiveSubIndex, $"Removed anonymous from UpdateSlow: {onUpdate.Target} : {onUpdate.Method}"); |
|||
return; |
|||
} |
|||
|
|||
stopwatch.Restart(); |
|||
onUpdate?.Invoke(dt); |
|||
stopwatch.Stop(); |
|||
if (stopwatch.ElapsedMilliseconds > m_durationToleranceMs) |
|||
{ |
|||
if (!m_doNotRemoveIfTooLong) |
|||
Remove(m_nextActiveSubIndex, $"UpdateSlow subscriber took too long, removing: {onUpdate.Target} : {onUpdate.Method}"); |
|||
else |
|||
{ |
|||
Debug.LogWarning($"UpdateSlow subscriber took too long: {onUpdate.Target} : {onUpdate.Method}"); |
|||
Increment(); |
|||
} |
|||
} |
|||
else |
|||
Increment(); |
|||
|
|||
void Remove(int index, string msg) |
|||
{ |
|||
m_subscribers.RemoveAt(index); |
|||
m_nextActiveSubIndex--; |
|||
Debug.LogError(msg); |
|||
Increment(); |
|||
} |
|||
void Increment() |
|||
{ |
|||
m_nextActiveSubIndex++; |
|||
if (m_nextActiveSubIndex >= m_subscribers.Count) |
|||
m_nextActiveSubIndex = 0; |
|||
} |
|||
} |
|||
|
|||
public void OnReProvided(IUpdateSlow prevUpdateSlow) |
|||
{ |
|||
if (prevUpdateSlow is UpdateSlow) |
|||
m_subscribers.AddRange((prevUpdateSlow as UpdateSlow).m_subscribers); |
|||
} |
|||
} |
|||
} |
|||
using System.Collections.Generic; |
|||
using UnityEngine; |
|||
using Stopwatch = System.Diagnostics.Stopwatch; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
public delegate void UpdateMethod(float dt); |
|||
|
|||
public interface IUpdateSlow : IProvidable<IUpdateSlow> |
|||
{ |
|||
void OnUpdate(float dt); |
|||
void Subscribe(UpdateMethod onUpdate); |
|||
void Unsubscribe(UpdateMethod onUpdate); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// A default implementation.
|
|||
/// </summary>
|
|||
public class UpdateSlowNoop : IUpdateSlow |
|||
{ |
|||
public void OnUpdate(float dt) { } |
|||
public void Subscribe(UpdateMethod onUpdate) { } |
|||
public void Unsubscribe(UpdateMethod onUpdate) { } |
|||
public void OnReProvided(IUpdateSlow prev) { } |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Some objects might need to be on a slower update loop than the usual MonoBehaviour Update, e.g. to refresh data from services.
|
|||
/// Some might also not want to be coupled to a Unity object at all but still need an update loop.
|
|||
/// </summary>
|
|||
public class UpdateSlow : MonoBehaviour, IUpdateSlow |
|||
{ |
|||
[SerializeField] |
|||
[Tooltip("Update interval. Note that lobby Get requests must occur at least 1 second apart, so this period should likely be greater than that.")] |
|||
private float m_updatePeriod = 1.5f; |
|||
[SerializeField] |
|||
[Tooltip("If a subscriber to slow update takes longer than this to execute, it can be automatically unsubscribed.")] |
|||
private float m_durationToleranceMs = 10; |
|||
[SerializeField] |
|||
[Tooltip("We ordinarily automatically remove a subscriber that takes too long. Otherwise, we'll simply log.")] |
|||
private bool m_doNotRemoveIfTooLong = false; |
|||
private List<UpdateMethod> m_subscribers = new List<UpdateMethod>(); |
|||
private float m_updateTimer = 0; |
|||
private int m_nextActiveSubIndex = 0; // For staggering subscribers, to prevent spikes of lots of things triggering at once.
|
|||
|
|||
public void Awake() |
|||
{ |
|||
Locator.Get.Provide(this); |
|||
} |
|||
public void OnDestroy() |
|||
{ |
|||
// We should clean up references in case they would prevent garbage collection.
|
|||
m_subscribers.Clear(); |
|||
} |
|||
|
|||
/// <summary>Don't assume that onUpdate will be called in any particular order compared to other subscribers.</summary>
|
|||
public void Subscribe(UpdateMethod onUpdate) |
|||
{ |
|||
if (!m_subscribers.Contains(onUpdate)) |
|||
m_subscribers.Add(onUpdate); |
|||
} |
|||
/// <summary>Safe to call even if onUpdate was not previously Subscribed.</summary>
|
|||
public void Unsubscribe(UpdateMethod onUpdate) |
|||
{ |
|||
int index = m_subscribers.IndexOf(onUpdate); |
|||
if (index >= 0) |
|||
{ |
|||
m_subscribers.Remove(onUpdate); |
|||
if (index < m_nextActiveSubIndex) |
|||
m_nextActiveSubIndex--; |
|||
} |
|||
} |
|||
|
|||
private void Update() |
|||
{ |
|||
if (m_subscribers.Count == 0) |
|||
return; |
|||
m_updateTimer += Time.deltaTime; |
|||
float effectivePeriod = m_updatePeriod / m_subscribers.Count; |
|||
while (m_updateTimer > effectivePeriod) |
|||
{ |
|||
m_updateTimer -= effectivePeriod; |
|||
OnUpdate(effectivePeriod); |
|||
} |
|||
} |
|||
|
|||
public void OnUpdate(float dt) |
|||
{ |
|||
Stopwatch stopwatch = new Stopwatch(); |
|||
m_nextActiveSubIndex = System.Math.Max(0, System.Math.Min(m_subscribers.Count - 1, m_nextActiveSubIndex)); // Just a backup.
|
|||
UpdateMethod onUpdate = m_subscribers[m_nextActiveSubIndex]; |
|||
if (onUpdate == null || onUpdate.Target == null) // In case something forgets to Unsubscribe when it dies.
|
|||
{ Remove(m_nextActiveSubIndex, $"Did not Unsubscribe from UpdateSlow: {onUpdate.Target} : {onUpdate.Method}"); |
|||
return; |
|||
} |
|||
if (onUpdate.Method.ToString().Contains("<")) // Detect an anonymous or lambda or local method that cannot be Unsubscribed, by checking for a character that can't exist in a declared method name.
|
|||
{ Remove(m_nextActiveSubIndex, $"Removed anonymous from UpdateSlow: {onUpdate.Target} : {onUpdate.Method}"); |
|||
return; |
|||
} |
|||
|
|||
stopwatch.Restart(); |
|||
onUpdate?.Invoke(dt); |
|||
stopwatch.Stop(); |
|||
if (stopwatch.ElapsedMilliseconds > m_durationToleranceMs) |
|||
{ |
|||
if (!m_doNotRemoveIfTooLong) |
|||
Remove(m_nextActiveSubIndex, $"UpdateSlow subscriber took too long, removing: {onUpdate.Target} : {onUpdate.Method}"); |
|||
else |
|||
{ |
|||
Debug.LogWarning($"UpdateSlow subscriber took too long: {onUpdate.Target} : {onUpdate.Method}"); |
|||
Increment(); |
|||
} |
|||
} |
|||
else |
|||
Increment(); |
|||
|
|||
void Remove(int index, string msg) |
|||
{ |
|||
m_subscribers.RemoveAt(index); |
|||
m_nextActiveSubIndex--; |
|||
Debug.LogError(msg); |
|||
Increment(); |
|||
} |
|||
void Increment() |
|||
{ |
|||
m_nextActiveSubIndex++; |
|||
if (m_nextActiveSubIndex >= m_subscribers.Count) |
|||
m_nextActiveSubIndex = 0; |
|||
} |
|||
} |
|||
|
|||
public void OnReProvided(IUpdateSlow prevUpdateSlow) |
|||
{ |
|||
if (prevUpdateSlow is UpdateSlow) |
|||
m_subscribers.AddRange((prevUpdateSlow as UpdateSlow).m_subscribers); |
|||
} |
|||
} |
|||
} |
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
public class LocalLobbyObserver : ObserverBehaviour<LocalLobby> { } |
|||
} |
|
|||
using LobbyRelaySample; |
|||
using NUnit.Framework; |
|||
using System.Collections; |
|||
using Unity.Services.Rooms; |
|||
using Unity.Services.Rooms.Models; |
|||
using UnityEngine; |
|||
using UnityEngine.TestTools; |
|||
using LobbyAPIInterface = LobbyRelaySample.Lobby.LobbyAPIInterface; |
|||
|
|||
namespace Test |
|||
{ |
|||
public class LobbyReadyCheckTests |
|||
{ |
|||
private string m_workingLobbyId; |
|||
private LobbyRelaySample.Auth.Identity m_auth; |
|||
private bool m_didSigninComplete = false; |
|||
private GameObject m_updateSlowObj; |
|||
|
|||
[OneTimeSetUp] |
|||
public void Setup() |
|||
{ |
|||
m_auth = new LobbyRelaySample.Auth.Identity(() => { m_didSigninComplete = true; }); |
|||
Locator.Get.Provide(m_auth); |
|||
m_updateSlowObj = new GameObject("UpdateSlowTest"); |
|||
m_updateSlowObj.AddComponent<UpdateSlow>(); |
|||
} |
|||
|
|||
[UnityTearDown] |
|||
public IEnumerator PerTestTeardown() |
|||
{ |
|||
if (m_workingLobbyId != null) |
|||
{ LobbyAPIInterface.DeleteLobbyAsync(m_workingLobbyId, null); |
|||
m_workingLobbyId = null; |
|||
} |
|||
yield return new WaitForSeconds(0.5f); // We need a yield anyway, so wait long enough to probably delete the lobby. There currently (6/22/2021) aren't other tests that would have issues if this took longer.
|
|||
} |
|||
|
|||
[OneTimeTearDown] |
|||
public void Teardown() |
|||
{ |
|||
Locator.Get.Provide(new LobbyRelaySample.Auth.IdentityNoop()); |
|||
m_auth.Dispose(); |
|||
LogAssert.ignoreFailingMessages = false; |
|||
LobbyAsyncRequests.Instance.EndTracking(); |
|||
GameObject.Destroy(m_updateSlowObj); |
|||
} |
|||
|
|||
private IEnumerator WaitForSignin() |
|||
{ |
|||
// Wait a reasonable amount of time for sign-in to complete.
|
|||
if (!m_didSigninComplete) |
|||
yield return new WaitForSeconds(3); |
|||
if (!m_didSigninComplete) |
|||
Assert.Fail("Did not sign in."); |
|||
} |
|||
|
|||
private IEnumerator CreateLobby(string lobbyName, string userId) |
|||
{ |
|||
Response<Room> createResponse = null; |
|||
float timeout = 5; |
|||
LobbyAPIInterface.CreateLobbyAsync(userId, lobbyName, 4, false, (r) => { createResponse = r; }); |
|||
while (createResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (lobby creation)."); |
|||
m_workingLobbyId = createResponse.Result.Id; |
|||
} |
|||
|
|||
private IEnumerator PushPlayerData(LobbyUser player) |
|||
{ |
|||
bool hasPushedPlayerData = false; |
|||
float timeout = 5; |
|||
LobbyAsyncRequests.Instance.UpdatePlayerDataAsync(LobbyRelaySample.Lobby.ToLocalLobby.RetrieveUserData(player), () => { hasPushedPlayerData = true; }); // LobbyContentHeartbeat normally does this.
|
|||
while (!hasPushedPlayerData && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (push player data)."); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// After creating a lobby and a player, signal that the player is Ready. This should lead to a countdown time being set for all players.
|
|||
/// </summary>
|
|||
[UnityTest] |
|||
public IEnumerator SetCountdownTimeSinglePlayer() |
|||
{ |
|||
LogAssert.ignoreFailingMessages = true; // Not sure why, but when auth logs in, it sometimes generates an error: "A Native Collection has not been disposed[...]." We don't want this to cause test failures, since in practice it *seems* to not negatively impact behavior.
|
|||
ReadyCheck readyCheck = new ReadyCheck(5); // This ready time is used for the countdown target end, not for any of the timing of actually detecting readies.
|
|||
yield return WaitForSignin(); |
|||
|
|||
string userId = m_auth.GetSubIdentity(LobbyRelaySample.Auth.IIdentityType.Auth).GetContent("id"); |
|||
yield return CreateLobby("TestReadyLobby1", userId); |
|||
|
|||
LobbyAsyncRequests.Instance.BeginTracking(m_workingLobbyId); |
|||
yield return new WaitForSeconds(2); // Allow the initial lobby retrieval.
|
|||
|
|||
LobbyUser user = new LobbyUser(); |
|||
user.ID = userId; |
|||
user.UserStatus = UserStatus.Ready; |
|||
yield return PushPlayerData(user); |
|||
|
|||
readyCheck.BeginCheckingForReady(); |
|||
float timeout = 5; // Long enough for two slow updates
|
|||
yield return new WaitForSeconds(timeout); |
|||
|
|||
readyCheck.Dispose(); |
|||
LobbyAsyncRequests.Instance.EndTracking(); |
|||
|
|||
yield return new WaitForSeconds(2); // Buffer to prevent a 429 on the upcoming Get, since there's a Get request on the slow upate loop when that's active.
|
|||
Response<Room> getResponse = null; |
|||
timeout = 5; |
|||
LobbyAPIInterface.GetLobbyAsync(m_workingLobbyId, (r) => { getResponse = r; }); |
|||
while (getResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (get lobby)."); |
|||
Assert.NotNull(getResponse.Result, "Retrieved lobby successfully."); |
|||
Assert.NotNull(getResponse.Result.Data, "Lobby should have data."); |
|||
|
|||
Assert.True(getResponse.Result.Data.ContainsKey("AllPlayersReady"), "Check for AllPlayersReady key."); |
|||
string readyString = getResponse.Result.Data["AllPlayersReady"]?.Value; |
|||
Assert.NotNull(readyString, "Check for non-null AllPlayersReady."); |
|||
Assert.True(long.TryParse(readyString, out long ticks), "Check for ticks value in AllPlayersReady."); // This will be based on the current time, so we won't check for a specific value.
|
|||
} |
|||
|
|||
// Can't test with multiple players on one machine, since anonymous UAS credentials can't be manually supplied.
|
|||
} |
|||
} |
|
|||
using NUnit.Framework; |
|||
using System.Collections; |
|||
using System.Linq; |
|||
using Unity.Services.Rooms; |
|||
using Unity.Services.Rooms.Models; |
|||
using UnityEngine; |
|||
using UnityEngine.TestTools; |
|||
using LobbyAPIInterface = LobbyRelaySample.Lobby.LobbyAPIInterface; |
|||
|
|||
namespace Test |
|||
{ |
|||
/// <summary>
|
|||
/// Hits the Authentication and Lobbies services in order to ensure lobbies can be created and deleted.
|
|||
/// The actual code accessing lobbies should go through LobbyAsyncRequests.
|
|||
/// </summary>
|
|||
public class LobbyRoundtripTests |
|||
{ |
|||
private string m_workingLobbyId; |
|||
private LobbyRelaySample.Auth.SubIdentity_Authentication m_auth; |
|||
private bool m_didSigninComplete = false; |
|||
|
|||
[OneTimeSetUp] |
|||
public void Setup() |
|||
{ |
|||
m_auth = new LobbyRelaySample.Auth.SubIdentity_Authentication(() => { m_didSigninComplete = true; }); |
|||
} |
|||
|
|||
[UnityTearDown] |
|||
public IEnumerator PerTestTeardown() |
|||
{ |
|||
if (m_workingLobbyId != null) |
|||
{ LobbyAPIInterface.DeleteLobbyAsync(m_workingLobbyId, null); |
|||
m_workingLobbyId = null; |
|||
} |
|||
yield return new WaitForSeconds(0.5f); // We need a yield anyway, so wait long enough to probably delete the lobby. There currently (6/22/2021) aren't other tests that would have issues if this took longer.
|
|||
} |
|||
|
|||
[OneTimeTearDown] |
|||
public void Teardown() |
|||
{ |
|||
m_auth?.Dispose(); |
|||
LogAssert.ignoreFailingMessages = false; |
|||
} |
|||
|
|||
[UnityTest] |
|||
public IEnumerator DoRoundtrip() |
|||
{ |
|||
LogAssert.ignoreFailingMessages = true; // Not sure why, but when auth logs in, it sometimes generates an error: "A Native Collection has not been disposed[...]." We don't want this to cause test failures, since in practice it *seems* to not negatively impact behavior.
|
|||
|
|||
// Wait a reasonable amount of time for sign-in to complete.
|
|||
if (!m_didSigninComplete) |
|||
yield return new WaitForSeconds(3); |
|||
if (!m_didSigninComplete) |
|||
Assert.Fail("Did not sign in."); |
|||
|
|||
// Since we're signed in through the same pathway as the actual game, the list of lobbies will include any that have been made in the game itself, so we should account for those.
|
|||
// If you want to get around this, consider having a secondary project using the same assets with its own credentials.
|
|||
yield return new WaitForSeconds(1); // To prevent a possible 429 with the upcoming Query request, in case a previous test had one; Query requests can only occur at a rate of 1 per second.
|
|||
Response<QueryResponse> queryResponse = null; |
|||
float timeout = 5; |
|||
LobbyAPIInterface.QueryAllLobbiesAsync((qr) => { queryResponse = qr; }); |
|||
while (queryResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (query #0)"); |
|||
Assert.IsTrue(queryResponse.Status >= 200 && queryResponse.Status < 300, "QueryAllLobbiesAsync should return a success code. (#0)"); |
|||
int numLobbiesIni = queryResponse.Result.Results?.Count ?? 0; |
|||
|
|||
// Create a test lobby.
|
|||
Response<Room> createResponse = null; |
|||
timeout = 5; |
|||
string lobbyName = "TestLobby-JustATest-123"; |
|||
LobbyAPIInterface.CreateLobbyAsync(m_auth.GetContent("id"), lobbyName, 100, false, (r) => { createResponse = r; }); |
|||
while (createResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (create)"); |
|||
Assert.IsTrue(createResponse.Status >= 200 && createResponse.Status < 300, "CreateLobbyAsync should return a success code."); |
|||
m_workingLobbyId = createResponse.Result.Id; |
|||
Assert.AreEqual(lobbyName, createResponse.Result.Name, "Created lobby should match the provided name."); |
|||
|
|||
// Query for the test lobby via QueryAllLobbies.
|
|||
yield return new WaitForSeconds(1); // To prevent a possible 429 with the upcoming Query request.
|
|||
queryResponse = null; |
|||
timeout = 5; |
|||
LobbyAPIInterface.QueryAllLobbiesAsync((qr) => { queryResponse = qr; }); |
|||
while (queryResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (query #1)"); |
|||
Assert.IsTrue(queryResponse.Status >= 200 && queryResponse.Status < 300, "QueryAllLobbiesAsync should return a success code. (#1)"); |
|||
Assert.AreEqual(1 + numLobbiesIni, queryResponse.Result.Results.Count, "Queried lobbies list should contain the test lobby."); |
|||
Assert.IsTrue(queryResponse.Result.Results.Where(r => r.Name == lobbyName).Count() == 1, "Checking queried lobby for name."); |
|||
Assert.IsTrue(queryResponse.Result.Results.Where(r => r.Id == m_workingLobbyId).Count() == 1, "Checking queried lobby for ID."); |
|||
|
|||
// Query for solely the test lobby via GetLobby.
|
|||
Response<Room> getResponse = null; |
|||
timeout = 5; |
|||
LobbyAPIInterface.GetLobbyAsync(createResponse.Result.Id, (r) => { getResponse = r; }); |
|||
while (getResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (get)"); |
|||
Assert.IsTrue(getResponse.Status >= 200 && getResponse.Status < 300, "GetLobbyAsync should return a success code."); |
|||
Assert.AreEqual(lobbyName, getResponse.Result.Name, "Checking the lobby we got for name."); |
|||
Assert.AreEqual(m_workingLobbyId, getResponse.Result.Id, "Checking the lobby we got for ID."); |
|||
|
|||
// Delete the test lobby.
|
|||
Response deleteResponse = null; |
|||
timeout = 5; |
|||
LobbyAPIInterface.DeleteLobbyAsync(m_workingLobbyId, (r) => { deleteResponse = r; }); |
|||
while (deleteResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (delete)"); |
|||
Assert.IsTrue(deleteResponse.Status >= 200 && deleteResponse.Status < 300, "DeleteLobbyAsync should return a success code."); |
|||
m_workingLobbyId = null; |
|||
|
|||
// Query to ensure the lobby is gone.
|
|||
yield return new WaitForSeconds(1); // To prevent a possible 429 with the upcoming Query request.
|
|||
Response<QueryResponse> queryResponseTwo = null; |
|||
timeout = 5; |
|||
LobbyAPIInterface.QueryAllLobbiesAsync((qr) => { queryResponseTwo = qr; }); |
|||
while (queryResponseTwo == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (query #2)"); |
|||
Assert.IsTrue(queryResponseTwo.Status >= 200 && queryResponseTwo.Status < 300, "QueryAllLobbiesAsync should return a success code. (#2)"); |
|||
Assert.AreEqual(numLobbiesIni, queryResponseTwo.Result.Results.Count, "Queried lobbies list should be empty."); |
|||
|
|||
// Some error messages might be asynchronous, so to reduce spillover into other tests, just wait here for a bit before proceeding.
|
|||
yield return new WaitForSeconds(3); |
|||
LogAssert.ignoreFailingMessages = false; |
|||
} |
|||
|
|||
[UnityTest] |
|||
public IEnumerator OnCompletesOnFailure() |
|||
{ |
|||
LogAssert.ignoreFailingMessages = true; |
|||
if (!m_didSigninComplete) |
|||
yield return new WaitForSeconds(3); |
|||
if (!m_didSigninComplete) |
|||
Assert.Fail("Did not sign in."); |
|||
|
|||
bool? didComplete = null; |
|||
LobbyAPIInterface.CreateLobbyAsync("ThisStringIsInvalidHere", "lobby name", 123, false, (r) => { didComplete = (r == null); }); |
|||
float timeout = 5; |
|||
while (didComplete == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check"); |
|||
Assert.NotNull(didComplete, "Should have called onComplete, even if the async request failed."); |
|||
Assert.True(didComplete, "The returned object will be null, so expect to need to handle it."); |
|||
} |
|||
} |
|||
} |
|
|||
using TMPro; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Watches a lobby or relay code for updates, displaying the current code to lobby members.
|
|||
/// </summary>
|
|||
public class DisplayCodeUI : ObserverPanel<LocalLobby> |
|||
{ |
|||
public enum CodeType { Lobby = 0, Relay = 1 } |
|||
|
|||
[SerializeField] |
|||
TMP_InputField m_outputText; |
|||
[SerializeField] |
|||
CodeType m_codeType; |
|||
|
|||
public override void ObservedUpdated(LocalLobby observed) |
|||
{ |
|||
string code = m_codeType == CodeType.Lobby ? observed.LobbyCode : observed.RelayCode; |
|||
|
|||
if (!string.IsNullOrEmpty(code)) |
|||
{ |
|||
m_outputText.text = code; |
|||
Show(); |
|||
} |
|||
else |
|||
{ |
|||
Hide(); |
|||
} |
|||
} |
|||
} |
|||
} |
|
|||
using System.Collections.Generic; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Contains the InLobbyUserUI instances while showing the UI for a lobby.
|
|||
/// </summary>
|
|||
[RequireComponent(typeof(LocalLobbyObserver))] |
|||
public class InLobbyUserList : ObserverPanel<LocalLobby> |
|||
{ |
|||
[SerializeField] |
|||
List<InLobbyUserUI> m_UserUIObjects = new List<InLobbyUserUI>(); |
|||
List<string> m_CurrentUsers = new List<string>(); // Just for keeping track more easily of which users are already displayed.
|
|||
|
|||
/// <summary>
|
|||
/// When the observed data updates, we need to detect changes to the list of players.
|
|||
/// </summary>
|
|||
public override void ObservedUpdated(LocalLobby observed) |
|||
{ |
|||
for (int id = m_CurrentUsers.Count - 1; id >= 0; id--) // We might remove users if they aren't in the new data, so iterate backwards.
|
|||
{ |
|||
string userId = m_CurrentUsers[id]; |
|||
if (!observed.LobbyUsers.ContainsKey(userId)) |
|||
{ |
|||
foreach (var ui in m_UserUIObjects) |
|||
{ |
|||
if (ui.UserId == userId) |
|||
{ |
|||
ui.OnUserLeft(); |
|||
OnUserLeft(userId); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
|
|||
foreach (var lobbyUserKvp in observed.LobbyUsers) // If there are new players, we need to hook them into the UI.
|
|||
{ |
|||
if (m_CurrentUsers.Contains(lobbyUserKvp.Key)) |
|||
continue; |
|||
m_CurrentUsers.Add(lobbyUserKvp.Key); |
|||
|
|||
foreach (var pcu in m_UserUIObjects) |
|||
{ |
|||
if (pcu.IsAssigned) |
|||
continue; |
|||
pcu.SetUser(lobbyUserKvp.Value); |
|||
break; |
|||
} |
|||
} |
|||
} |
|||
|
|||
void OnUserLeft(string userID) |
|||
{ |
|||
if (!m_CurrentUsers.Contains(userID)) |
|||
return; |
|||
m_CurrentUsers.Remove(userID); |
|||
} |
|||
} |
|||
} |
|
|||
using TMPro; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Displays the name of the lobby.
|
|||
/// </summary>
|
|||
public class LobbyNameUI : ObserverPanel<LocalLobby> |
|||
{ |
|||
[SerializeField] |
|||
TMP_Text m_lobbyNameText; |
|||
|
|||
public override void ObservedUpdated(LocalLobby observed) |
|||
{ |
|||
m_lobbyNameText.SetText(observed.LobbyName); |
|||
} |
|||
} |
|||
} |
|
|||
using TMPro; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Displays the IP when connected to Relay.
|
|||
/// </summary>
|
|||
public class RelayAddressUI : ObserverPanel<LocalLobby> |
|||
{ |
|||
[SerializeField] |
|||
TMP_Text m_IPAddressText; |
|||
|
|||
public override void ObservedUpdated(LocalLobby observed) |
|||
{ |
|||
m_IPAddressText.SetText(observed.RelayServer?.ToString()); |
|||
} |
|||
} |
|||
} |
|
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// UI element that is displayed when the lobby is in a particular state (e.g. counting down, in-game).
|
|||
/// </summary>
|
|||
public class ShowWhenLobbyStateUI : ObserverPanel<LocalLobby> |
|||
{ |
|||
[SerializeField] |
|||
private LobbyState m_ShowThisWhen; |
|||
|
|||
public override void ObservedUpdated(LocalLobby observed) |
|||
{ |
|||
if (m_ShowThisWhen.HasFlag(observed.State)) |
|||
Show(); |
|||
else |
|||
Hide(); |
|||
} |
|||
} |
|||
} |
|||
|
|
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Main menu start button.
|
|||
/// </summary>
|
|||
public class StartLobbyButtonUI : MonoBehaviour |
|||
{ |
|||
public void ToJoinMenu() |
|||
{ |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.ChangeGameState, GameState.JoinMenu); |
|||
} |
|||
} |
|||
} |
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Threading.Tasks; |
|||
using Unity.Services.Rooms; |
|||
using Unity.Services.Rooms.Models; |
|||
using Unity.Services.Rooms.Rooms; |
|||
|
|||
namespace LobbyRelaySample.Lobby |
|||
{ |
|||
/// <summary>
|
|||
/// Does all the interactions with the Lobby API.
|
|||
/// </summary>
|
|||
public static class LobbyAPIInterface |
|||
{ |
|||
private class InProgressRequest<T> |
|||
{ |
|||
public InProgressRequest(Task<T> task, Action<T> onComplete) |
|||
{ |
|||
DoRequest(task, onComplete); |
|||
} |
|||
|
|||
private async void DoRequest(Task<T> task, Action<T> onComplete) |
|||
{ |
|||
T result = default; |
|||
string currentTrace = System.Environment.StackTrace; |
|||
try { |
|||
result = await task; |
|||
} catch (Exception e) { |
|||
Exception eFull = new Exception($"Call stack before async call:\n{currentTrace}\n", e); |
|||
throw eFull; |
|||
} finally { |
|||
onComplete?.Invoke(result); |
|||
} |
|||
} |
|||
} |
|||
|
|||
private const int k_maxLobbiesToShow = 64; |
|||
|
|||
public static void CreateLobbyAsync(string requesterUASId, string lobbyName, int maxPlayers, bool isPrivate, Action<Response<Room>> onComplete) |
|||
{ |
|||
CreateRoomRequest createRequest = new CreateRoomRequest(new CreateRequest( |
|||
name: lobbyName, |
|||
player: new Unity.Services.Rooms.Models.Player(requesterUASId), |
|||
maxPlayers: maxPlayers, |
|||
isPrivate: isPrivate |
|||
)); |
|||
var task = RoomsService.RoomsApiClient.CreateRoomAsync(createRequest); |
|||
new InProgressRequest<Response<Room>>(task, onComplete); |
|||
} |
|||
|
|||
public static void DeleteLobbyAsync(string lobbyId, Action<Response> onComplete) |
|||
{ |
|||
DeleteRoomRequest deleteRequest = new DeleteRoomRequest(lobbyId); |
|||
var task = RoomsService.RoomsApiClient.DeleteRoomAsync(deleteRequest); |
|||
new InProgressRequest<Response>(task, onComplete); |
|||
} |
|||
|
|||
public static void JoinLobbyAsync(string requesterUASId, string lobbyId, string lobbyCode, Action<Response<Room>> onComplete) |
|||
{ |
|||
JoinRoomRequest joinRequest = new JoinRoomRequest(new JoinRequest( |
|||
player: new Unity.Services.Rooms.Models.Player(requesterUASId), |
|||
id: lobbyId, |
|||
roomCode: lobbyCode |
|||
)); |
|||
var task = RoomsService.RoomsApiClient.JoinRoomAsync(joinRequest); |
|||
new InProgressRequest<Response<Room>>(task, onComplete); |
|||
} |
|||
|
|||
public static void LeaveLobbyAsync(string requesterUASId, string lobbyId, Action<Response> onComplete) |
|||
{ |
|||
RemovePlayerRequest leaveRequest = new RemovePlayerRequest(lobbyId, requesterUASId); |
|||
var task = RoomsService.RoomsApiClient.RemovePlayerAsync(leaveRequest); |
|||
new InProgressRequest<Response>(task, onComplete); |
|||
} |
|||
|
|||
public static void QueryAllLobbiesAsync(Action<Response<QueryResponse>> onComplete) |
|||
{ |
|||
QueryRoomsRequest queryRequest = new QueryRoomsRequest(new QueryRequest(count: k_maxLobbiesToShow)); |
|||
var task = RoomsService.RoomsApiClient.QueryRoomsAsync(queryRequest); |
|||
new InProgressRequest<Response<QueryResponse>>(task, onComplete); |
|||
} |
|||
|
|||
public static void GetLobbyAsync(string lobbyId, Action<Response<Room>> onComplete) |
|||
{ |
|||
GetRoomRequest getRequest = new GetRoomRequest(lobbyId); |
|||
var task = RoomsService.RoomsApiClient.GetRoomAsync(getRequest); |
|||
new InProgressRequest<Response<Room>>(task, onComplete); |
|||
} |
|||
|
|||
public static void UpdateLobbyAsync(string lobbyId, Dictionary<string, DataObject> data, Action<Response<Room>> onComplete) |
|||
{ |
|||
UpdateRoomRequest updateRequest = new UpdateRoomRequest(lobbyId, new UpdateRequest( |
|||
data: data |
|||
)); |
|||
var task = RoomsService.RoomsApiClient.UpdateRoomAsync(updateRequest); |
|||
new InProgressRequest<Response<Room>>(task, onComplete); |
|||
} |
|||
|
|||
public static void UpdatePlayerAsync(string lobbyId, string playerId, Dictionary<string, PlayerDataObject> data, Action<Response<Room>> onComplete) |
|||
{ |
|||
UpdatePlayerRequest updateRequest = new UpdatePlayerRequest(lobbyId, playerId, new PlayerUpdateRequest( |
|||
data: data |
|||
)); |
|||
var task = RoomsService.RoomsApiClient.UpdatePlayerAsync(updateRequest); |
|||
new InProgressRequest<Response<Room>>(task, onComplete); |
|||
} |
|||
} |
|||
} |
|
|||
using LobbyRelaySample.Lobby; |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using Unity.Services.Authentication; |
|||
using Unity.Services.Rooms; |
|||
using Unity.Services.Rooms.Models; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// An abstraction layer between the direct calls into the Lobby API and the outcomes you actually want. E.g. you can request to get a readable list of
|
|||
/// current lobbies and not need to make the query call directly.
|
|||
/// </summary>
|
|||
public class LobbyAsyncRequests |
|||
{ |
|||
// Just doing a singleton since static access is all that's really necessary but we also need to be able to subscribe to the slow update loop.
|
|||
private static LobbyAsyncRequests s_instance; |
|||
|
|||
public static LobbyAsyncRequests Instance |
|||
{ |
|||
get |
|||
{ |
|||
if (s_instance == null) |
|||
s_instance = new LobbyAsyncRequests(); |
|||
return s_instance; |
|||
} |
|||
} |
|||
|
|||
public LobbyAsyncRequests() |
|||
{ |
|||
Locator.Get.UpdateSlow.Subscribe(UpdateLobby); // Shouldn't need to unsubscribe since this instance won't be replaced.
|
|||
} |
|||
|
|||
private static bool IsSuccessful(Response response) |
|||
{ |
|||
return response != null && response.Status >= 200 && response.Status < 300; // Uses HTTP status codes, so 2xx is a success.
|
|||
} |
|||
|
|||
#region We want to cache the lobby object so we don't query for it every time we need to do a different lobby operation or view current data.
|
|||
// (This assumes that the player will be actively in just one lobby at a time, though they could passively be in more.)
|
|||
private Queue<Action> m_pendingOperations = new Queue<Action>(); |
|||
private string m_currentLobbyId = null; |
|||
private Room m_lastKnownLobby; |
|||
private bool m_isMidRetrieve = false; |
|||
public Room CurrentLobby => m_lastKnownLobby; |
|||
|
|||
public void BeginTracking(string lobbyId) |
|||
{ |
|||
m_currentLobbyId = lobbyId; |
|||
} |
|||
|
|||
public void EndTracking() |
|||
{ |
|||
m_currentLobbyId = null; |
|||
} |
|||
|
|||
private void UpdateLobby(float unused) |
|||
{ |
|||
if (!string.IsNullOrEmpty(m_currentLobbyId)) |
|||
RetrieveLobbyAsync(m_currentLobbyId, OnComplete); |
|||
|
|||
void OnComplete(Room lobby) |
|||
{ |
|||
if (lobby != null) |
|||
m_lastKnownLobby = lobby; |
|||
m_isMidRetrieve = false; |
|||
HandlePendingOperations(); |
|||
} |
|||
} |
|||
|
|||
private void HandlePendingOperations() |
|||
{ |
|||
while (m_pendingOperations.Count > 0) |
|||
m_pendingOperations.Dequeue()?.Invoke(); // Note: If this ends up enqueuing a bunch of operations, we might need to batch them and/or ensure they don't all execute at once.
|
|||
} |
|||
|
|||
#endregion
|
|||
|
|||
/// <summary>
|
|||
/// Attempt to create a new lobby and then join it.
|
|||
/// </summary>
|
|||
public void CreateLobbyAsync(string lobbyName, int maxPlayers, bool isPrivate, Action<Room> onSuccess, Action onFailure) |
|||
{ |
|||
string uasId = AuthenticationService.Instance.PlayerId; |
|||
LobbyAPIInterface.CreateLobbyAsync(uasId, lobbyName, maxPlayers, isPrivate, OnLobbyCreated); |
|||
|
|||
void OnLobbyCreated(Response<Room> response) |
|||
{ |
|||
if (!IsSuccessful(response)) |
|||
onFailure?.Invoke(); |
|||
else |
|||
{ |
|||
var pendingLobby = response.Result; |
|||
onSuccess?.Invoke(pendingLobby); // The Create request automatically joins the lobby, so we need not take further action.
|
|||
} |
|||
} |
|||
} |
|||
|
|||
/// <summary>Attempt to join an existing lobby. Either ID xor code can be null.</summary>
|
|||
public void JoinLobbyAsync(string lobbyId, string lobbyCode, Action<Room> onSuccess, Action onFailure) |
|||
{ |
|||
string uasId = AuthenticationService.Instance.PlayerId; |
|||
LobbyAPIInterface.JoinLobbyAsync(uasId, lobbyId, lobbyCode, OnLobbyJoined); |
|||
|
|||
void OnLobbyJoined(Response<Room> response) |
|||
{ |
|||
if (!IsSuccessful(response)) |
|||
onFailure?.Invoke(); |
|||
else |
|||
onSuccess?.Invoke(response?.Result); |
|||
} |
|||
} |
|||
|
|||
/// <summary>Used for getting the list of all active lobbies, without needing full info for each.</summary>
|
|||
/// <param name="onListRetrieved">If called with null, retrieval was unsuccessful. Else, this will be given a list of contents to display, as pairs of a lobby code and a display string for that lobby.</param>
|
|||
public void RetrieveLobbyListAsync(Action<QueryResponse> onListRetrieved, Action<Response<QueryResponse>> onError = null) |
|||
{ |
|||
LobbyAPIInterface.QueryAllLobbiesAsync(OnLobbyListRetrieved); |
|||
|
|||
void OnLobbyListRetrieved(Response<QueryResponse> response) |
|||
{ |
|||
if (IsSuccessful(response)) |
|||
onListRetrieved?.Invoke(response?.Result); |
|||
else |
|||
onError?.Invoke(response); |
|||
} |
|||
} |
|||
/// <param name="onComplete">If no lobby is retrieved, this is given null.</param>
|
|||
private void RetrieveLobbyAsync(string lobbyId, Action<Room> onComplete) |
|||
{ |
|||
if (m_isMidRetrieve) |
|||
return; // Not calling onComplete since there's just the one point at which this is called.
|
|||
m_isMidRetrieve = true; |
|||
LobbyAPIInterface.GetLobbyAsync(lobbyId, OnGet); |
|||
|
|||
void OnGet(Response<Room> response) |
|||
{ |
|||
m_isMidRetrieve = false; |
|||
onComplete?.Invoke(response?.Result); |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Attempt to leave a lobby, and then delete it if no players remain.
|
|||
/// </summary>
|
|||
/// <param name="onComplete">Called once the request completes, regardless of success or failure.</param>
|
|||
public void LeaveLobbyAsync(string lobbyId, Action onComplete) |
|||
{ |
|||
string uasId = AuthenticationService.Instance.PlayerId; |
|||
LobbyAPIInterface.LeaveLobbyAsync(uasId, lobbyId, OnLeftLobby); |
|||
|
|||
void OnLeftLobby(Response response) |
|||
{ |
|||
onComplete?.Invoke(); |
|||
|
|||
// Lobbies will automatically delete the lobby if unoccupied, so we don't need to take further action.
|
|||
|
|||
// TEMP. As of 6/31/21, the lobbies service doesn't automatically delete emptied lobbies, though that functionality is expected in the near-term.
|
|||
// Until then, we'll do a delete request whenever we leave, and if it's invalid, we'll just get a 403 back.
|
|||
LobbyAPIInterface.DeleteLobbyAsync(lobbyId, null); |
|||
} |
|||
} |
|||
|
|||
/// <param name="data">Key-value pairs, which will overwrite any existing data for these keys. Presumed to be available to all lobby members but not publicly.</param>
|
|||
public void UpdatePlayerDataAsync(Dictionary<string, string> data, Action onComplete) |
|||
{ |
|||
if (!ShouldUpdateData(() => { UpdatePlayerDataAsync(data, onComplete); }, onComplete)) |
|||
return; |
|||
|
|||
Room lobby = m_lastKnownLobby; |
|||
Dictionary<string, PlayerDataObject> dataCurr = new Dictionary<string, PlayerDataObject>(); |
|||
foreach (var dataNew in data) |
|||
{ |
|||
PlayerDataObject dataObj = new PlayerDataObject(visibility: PlayerDataObject.VisibilityOptions.Member, value: dataNew.Value); |
|||
if (dataCurr.ContainsKey(dataNew.Key)) |
|||
dataCurr[dataNew.Key] = dataObj; |
|||
else |
|||
dataCurr.Add(dataNew.Key, dataObj); |
|||
} |
|||
|
|||
LobbyAPIInterface.UpdatePlayerAsync(lobby.Id, Locator.Get.Identity.GetSubIdentity(Auth.IIdentityType.Auth).GetContent("id"), dataCurr, (r) => { onComplete?.Invoke(); }); |
|||
} |
|||
|
|||
/// <param name="data">Key-value pairs, which will overwrite any existing data for these keys. Presumed to be available to all lobby members but not publicly.</param>
|
|||
public void UpdateLobbyDataAsync(Dictionary<string, string> data, Action onComplete) |
|||
{ |
|||
if (!ShouldUpdateData(() => { UpdateLobbyDataAsync(data, onComplete); }, onComplete)) |
|||
return; |
|||
|
|||
Room lobby = m_lastKnownLobby; |
|||
Dictionary<string, DataObject> dataCurr = lobby.Data ?? new Dictionary<string, DataObject>(); |
|||
foreach (var dataNew in data) |
|||
{ |
|||
DataObject dataObj = new DataObject(visibility: DataObject.VisibilityOptions.Public, value: dataNew.Value); // Public so that when we request the list of lobbies, we can get info about them for filtering.
|
|||
if (dataCurr.ContainsKey(dataNew.Key)) |
|||
dataCurr[dataNew.Key] = dataObj; |
|||
else |
|||
dataCurr.Add(dataNew.Key, dataObj); |
|||
} |
|||
|
|||
LobbyAPIInterface.UpdateLobbyAsync(lobby.Id, dataCurr, (r) => { onComplete?.Invoke(); }); |
|||
} |
|||
|
|||
private bool ShouldUpdateData(Action caller, Action onComplete) |
|||
{ |
|||
if (m_isMidRetrieve) |
|||
{ m_pendingOperations.Enqueue(caller); |
|||
return false; |
|||
} |
|||
Room lobby = m_lastKnownLobby; |
|||
if (lobby == null) |
|||
{ onComplete?.Invoke(); |
|||
return false; |
|||
} |
|||
return true; |
|||
} |
|||
} |
|||
} |
|
|||
using System; |
|||
using LobbyRemote = Unity.Services.Rooms.Models.Room; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Keep updated on changes to a joined lobby.
|
|||
/// </summary>
|
|||
public class LobbyContentHeartbeat |
|||
{ |
|||
private LocalLobby m_localLobby; |
|||
private LobbyUser m_localUser; |
|||
private bool m_isAwaitingQuery = false; |
|||
private bool m_shouldPushData = false; |
|||
|
|||
public void BeginTracking(LocalLobby lobby, LobbyUser localUser) |
|||
{ |
|||
m_localLobby = lobby; |
|||
m_localUser = localUser; |
|||
Locator.Get.UpdateSlow.Subscribe(OnUpdate); |
|||
m_localLobby.onChanged += OnLocalLobbyChanged; |
|||
m_shouldPushData = true; // Ensure the initial presence of a new player is pushed to the lobby; otherwise, when a non-host joins, the LocalLobby never receives their data until they push something new.
|
|||
} |
|||
|
|||
public void EndTracking() |
|||
{ |
|||
m_shouldPushData = false; |
|||
Locator.Get.UpdateSlow.Unsubscribe(OnUpdate); |
|||
if (m_localLobby != null) |
|||
m_localLobby.onChanged -= OnLocalLobbyChanged; |
|||
m_localLobby = null; |
|||
m_localUser = null; |
|||
} |
|||
|
|||
private void OnLocalLobbyChanged(LocalLobby changed) |
|||
{ |
|||
if (string.IsNullOrEmpty(changed.LobbyID)) // When the player leaves, their LocalLobby is cleared out but maintained.
|
|||
EndTracking(); |
|||
m_shouldPushData = true; |
|||
} |
|||
|
|||
public void OnUpdate(float dt) |
|||
{ |
|||
if (m_isAwaitingQuery || m_localLobby == null) |
|||
return; |
|||
|
|||
m_isAwaitingQuery = true; // Note that because we make async calls, if one of them fails and doesn't call our callback, this will never be reset to false.
|
|||
if (m_shouldPushData) |
|||
PushDataToLobby(); |
|||
else |
|||
OnRetrieve(); |
|||
|
|||
void PushDataToLobby() |
|||
{ |
|||
if (m_localUser == null) |
|||
{ |
|||
m_isAwaitingQuery = false; |
|||
return; // Don't revert m_shouldPushData yet, so that we can retry.
|
|||
} |
|||
m_shouldPushData = false; |
|||
|
|||
if (m_localUser.IsHost) |
|||
DoLobbyDataPush(); |
|||
else |
|||
DoPlayerDataPush(); |
|||
} |
|||
|
|||
void DoLobbyDataPush() |
|||
{ |
|||
LobbyAsyncRequests.Instance.UpdateLobbyDataAsync(Lobby.ToLocalLobby.RetrieveLobbyData(m_localLobby), () => { DoPlayerDataPush(); }); |
|||
} |
|||
|
|||
void DoPlayerDataPush() |
|||
{ |
|||
LobbyAsyncRequests.Instance.UpdatePlayerDataAsync(Lobby.ToLocalLobby.RetrieveUserData(m_localUser), () => { m_isAwaitingQuery = false; }); |
|||
} |
|||
|
|||
void OnRetrieve() |
|||
{ |
|||
m_isAwaitingQuery = false; |
|||
LobbyRemote lobby = LobbyAsyncRequests.Instance.CurrentLobby; |
|||
if (lobby == null) return; |
|||
bool prevShouldPush = m_shouldPushData; |
|||
var prevState = m_localLobby.State; |
|||
Lobby.ToLocalLobby.Convert(lobby, m_localLobby, m_localUser); |
|||
m_shouldPushData = prevShouldPush; |
|||
CheckForAllPlayersReady(); |
|||
|
|||
if (prevState != LobbyState.Lobby && m_localLobby.State == LobbyState.Lobby) |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.ToLobby, null); |
|||
} |
|||
|
|||
|
|||
void CheckForAllPlayersReady() |
|||
{ |
|||
bool areAllPlayersReady = m_localLobby.AllPlayersReadyTime != null; |
|||
if (areAllPlayersReady) |
|||
{ |
|||
long targetTimeTicks = m_localLobby.AllPlayersReadyTime.Value; |
|||
DateTime targetTime = new DateTime(targetTimeTicks); |
|||
if (targetTime.Subtract(DateTime.Now).Seconds < 0) |
|||
return; |
|||
|
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.Client_EndReadyCountdownAt, targetTime); // Note that this could be called multiple times.
|
|||
} |
|||
} |
|||
} |
|||
} |
|||
} |
|
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Keeps the lobby list updated automatically.
|
|||
/// </summary>
|
|||
public class LobbyListHeartbeat : MonoBehaviour |
|||
{ |
|||
public void SetActive(bool isActive) |
|||
{ |
|||
if (isActive) |
|||
Locator.Get.UpdateSlow.Subscribe(OnUpdate); |
|||
else |
|||
Locator.Get.UpdateSlow.Unsubscribe(OnUpdate); |
|||
} |
|||
|
|||
private void OnUpdate(float dt) |
|||
{ |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.QueryLobbies, null); |
|||
} |
|||
} |
|||
} |
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// On the host, this will watch for all players to ready, and once they have, it will prepare for a synchronized countdown.
|
|||
/// </summary>
|
|||
public class ReadyCheck : IDisposable |
|||
{ |
|||
float m_ReadyTime = 5; |
|||
|
|||
public ReadyCheck(float readyTime = 5) |
|||
{ |
|||
m_ReadyTime = readyTime; |
|||
} |
|||
|
|||
public void BeginCheckingForReady() |
|||
{ |
|||
Locator.Get.UpdateSlow.Subscribe(OnUpdate); |
|||
} |
|||
|
|||
public void EndCheckingForReady() |
|||
{ |
|||
Locator.Get.UpdateSlow.Unsubscribe(OnUpdate); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Checks the lobby to see if we have all Readied up. If so, send out a message with the target time at which to end a countdown.
|
|||
/// </summary>
|
|||
void OnUpdate(float dt) |
|||
{ |
|||
var lobby = LobbyAsyncRequests.Instance.CurrentLobby; |
|||
if (lobby == null || lobby.Players.Count == 0) |
|||
return; |
|||
|
|||
int readyCount = lobby.Players.Count((p) => |
|||
{ |
|||
if (p.Data?.ContainsKey("UserStatus") != true) // Needs to be "!= true" to handle null properly.
|
|||
return false; |
|||
UserStatus status; |
|||
if (Enum.TryParse(p.Data["UserStatus"].Value, out status)) |
|||
return status == UserStatus.Ready; |
|||
return false; |
|||
}); |
|||
|
|||
if (readyCount == lobby.Players.Count) |
|||
{ |
|||
Dictionary<string, string> data = new Dictionary<string, string>(); |
|||
DateTime targetTime = DateTime.Now.AddSeconds(m_ReadyTime); |
|||
data.Add("AllPlayersReady", targetTime.Ticks.ToString()); |
|||
LobbyAsyncRequests.Instance.UpdateLobbyDataAsync(data, null); |
|||
EndCheckingForReady(); |
|||
} |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
EndCheckingForReady(); |
|||
} |
|||
} |
|||
} |
|
|||
using System.Collections.Generic; |
|||
using Unity.Services.Rooms.Models; |
|||
|
|||
namespace LobbyRelaySample.Lobby |
|||
{ |
|||
/// <summary>
|
|||
/// Convert the lobby resulting from a request into a LocalLobby for use in the game logic.
|
|||
/// </summary>
|
|||
public static class ToLocalLobby |
|||
{ |
|||
/// <summary>
|
|||
/// Create a new LocalLobby from the content of a retrieved lobby. Its data can be copied into an existing LocalLobby for use.
|
|||
/// </summary>
|
|||
public static void Convert(Room lobby, LocalLobby outputToHere, LobbyUser existingLocalUser = null) |
|||
{ |
|||
LobbyInfo info = new LobbyInfo |
|||
{ LobbyID = lobby.Id, |
|||
LobbyCode = lobby.RoomCode, |
|||
Private = lobby.IsPrivate, |
|||
LobbyName = lobby.Name, |
|||
MaxPlayerCount = lobby.MaxPlayers, |
|||
RelayCode = lobby.Data?.ContainsKey("RelayCode") == true ? lobby.Data["RelayCode"].Value : null, |
|||
State = lobby.Data?.ContainsKey("State") == true ? (LobbyState) int.Parse(lobby.Data["State"].Value) : LobbyState.Lobby, |
|||
AllPlayersReadyTime = lobby.Data?.ContainsKey("AllPlayersReady") == true ? long.Parse(lobby.Data["AllPlayersReady"].Value) : (long?)null |
|||
}; |
|||
Dictionary<string, LobbyUser> lobbyUsers = new Dictionary<string, LobbyUser>(); |
|||
foreach (var player in lobby.Players) |
|||
{ |
|||
if (existingLocalUser != null && player.Id.Equals(existingLocalUser.ID)) |
|||
{ |
|||
existingLocalUser.IsHost = lobby.HostId.Equals(player.Id); |
|||
existingLocalUser.DisplayName = player.Data?.ContainsKey("DisplayName") == true ? player.Data["DisplayName"].Value : existingLocalUser.DisplayName; |
|||
existingLocalUser.Emote = player.Data?.ContainsKey("Emote") == true ? player.Data["Emote"].Value : existingLocalUser.Emote; |
|||
lobbyUsers.Add(existingLocalUser.ID, existingLocalUser); |
|||
} |
|||
else |
|||
{ |
|||
LobbyUser user = new LobbyUser( |
|||
displayName: player.Data?.ContainsKey("DisplayName") == true ? player.Data["DisplayName"].Value : "NewPlayer", |
|||
isHost: lobby.HostId.Equals(player.Id), |
|||
id: player.Id, |
|||
emote: player.Data?.ContainsKey("Emote") == true ? player.Data["Emote"].Value : null, |
|||
userStatus: player.Data?.ContainsKey("UserStatus") == true ? player.Data["UserStatus"].Value : UserStatus.Lobby.ToString() |
|||
); |
|||
lobbyUsers.Add(user.ID, user); |
|||
} |
|||
} |
|||
|
|||
outputToHere.CopyObserved(info, lobbyUsers); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Create a list of new LocalLobby from the content of a retrieved lobby.
|
|||
/// </summary>
|
|||
public static List<LocalLobby> Convert(QueryResponse response) |
|||
{ |
|||
List<LocalLobby> retLst = new List<LocalLobby>(); |
|||
foreach (var lobby in response.Results) |
|||
retLst.Add(Convert(lobby)); |
|||
return retLst; |
|||
} |
|||
private static LocalLobby Convert(Room lobby) |
|||
{ |
|||
LocalLobby data = new LocalLobby(); |
|||
Convert(lobby, data, null); |
|||
return data; |
|||
} |
|||
|
|||
public static Dictionary<string, string> RetrieveLobbyData(LocalLobby lobby) |
|||
{ |
|||
Dictionary<string, string> data = new Dictionary<string, string>(); |
|||
data.Add("RelayCode", lobby.RelayCode); |
|||
data.Add("State", ((int)lobby.State).ToString()); |
|||
// We only want the ArePlayersReadyTime to be set when we actually are ready for it, and it's null otherwise. So, don't set that here.
|
|||
return data; |
|||
} |
|||
|
|||
public static Dictionary<string, string> RetrieveUserData(LobbyUser user) |
|||
{ |
|||
Dictionary<string, string> data = new Dictionary<string, string>(); |
|||
if (user == null || string.IsNullOrEmpty(user.ID)) |
|||
return data; |
|||
data.Add("DisplayName", user.DisplayName); |
|||
data.Add("Emote", user.Emote); // Emote could be null, which is fine.
|
|||
data.Add("UserStatus", user.UserStatus.ToString()); |
|||
return data; |
|||
} |
|||
} |
|||
} |
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
public class LobbyDataObserver : ObserverBehaviour<LobbyData> { } |
|||
} |
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// On the host, this will watch for all players to ready, and once they have, it will prepare for a synchronized countdown.
|
|||
/// </summary>
|
|||
public class LobbyReadyCheck : IDisposable |
|||
{ |
|||
Action<bool> m_OnReadyCheckComplete; |
|||
|
|||
float m_ReadyTime = 5; |
|||
|
|||
public LobbyReadyCheck(Action<bool> onReadyCheckComplete = null, float readyTime = 5) |
|||
{ |
|||
m_OnReadyCheckComplete = onReadyCheckComplete; |
|||
m_ReadyTime = readyTime; |
|||
} |
|||
|
|||
public void BeginCheckingForReady() |
|||
{ |
|||
Locator.Get.UpdateSlow.Subscribe(OnUpdate); |
|||
} |
|||
|
|||
public void EndCheckingForReady() |
|||
{ |
|||
Locator.Get.UpdateSlow.Unsubscribe(OnUpdate); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Checks the lobby to see if we have all Readied up. If so, send out a message with the target time at which to end a countdown.
|
|||
/// </summary>
|
|||
void OnUpdate(float dt) |
|||
{ |
|||
var room = RoomsQuery.Instance.CurrentRoom; |
|||
if (room == null || room.Players.Count == 0) |
|||
return; |
|||
|
|||
|
|||
int readyCount = room.Players.Count((p) => |
|||
{ |
|||
if (p.Data?.ContainsKey("UserStatus") != true) // Needs to be "!= true" to handle null properly.
|
|||
return false; |
|||
UserStatus status; |
|||
if (Enum.TryParse(p.Data["UserStatus"].Value, out status)) |
|||
return status == UserStatus.Ready; |
|||
return false; |
|||
}); |
|||
|
|||
if (readyCount == room.Players.Count) |
|||
{ |
|||
Dictionary<string, string> data = new Dictionary<string, string>(); |
|||
DateTime targetTime = DateTime.Now.AddSeconds(m_ReadyTime); |
|||
data.Add("AllPlayersReady", targetTime.Ticks.ToString()); |
|||
RoomsQuery.Instance.UpdateRoomDataAsync(data, null); |
|||
EndCheckingForReady(); |
|||
} |
|||
} |
|||
|
|||
public void Dispose() |
|||
{ |
|||
EndCheckingForReady(); |
|||
} |
|||
} |
|||
} |
|
|||
using LobbyRelaySample; |
|||
using NUnit.Framework; |
|||
using System.Collections; |
|||
using Unity.Services.Rooms; |
|||
using Unity.Services.Rooms.Models; |
|||
using UnityEngine; |
|||
using UnityEngine.TestTools; |
|||
using RoomsInterface = LobbyRelaySample.Lobby.RoomsInterface; |
|||
|
|||
namespace Test |
|||
{ |
|||
public class ReadyCheckTests |
|||
{ |
|||
private string m_workingRoomId; |
|||
private LobbyRelaySample.Auth.Identity m_auth; |
|||
private bool m_didSigninComplete = false; |
|||
private GameObject m_updateSlowObj; |
|||
|
|||
[OneTimeSetUp] |
|||
public void Setup() |
|||
{ |
|||
m_auth = new LobbyRelaySample.Auth.Identity(() => { m_didSigninComplete = true; }); |
|||
Locator.Get.Provide(m_auth); |
|||
m_updateSlowObj = new GameObject("UpdateSlowTest"); |
|||
m_updateSlowObj.AddComponent<UpdateSlow>(); |
|||
} |
|||
|
|||
[UnityTearDown] |
|||
public IEnumerator PerTestTeardown() |
|||
{ |
|||
if (m_workingRoomId != null) |
|||
{ RoomsInterface.DeleteRoomAsync(m_workingRoomId, null); |
|||
m_workingRoomId = null; |
|||
} |
|||
yield return new WaitForSeconds(0.5f); // We need a yield anyway, so wait long enough to probably delete the room. There currently (6/22/2021) aren't other tests that would have issues if this took longer.
|
|||
} |
|||
|
|||
[OneTimeTearDown] |
|||
public void Teardown() |
|||
{ |
|||
Locator.Get.Provide(new LobbyRelaySample.Auth.IdentityNoop()); |
|||
m_auth.Dispose(); |
|||
LogAssert.ignoreFailingMessages = false; |
|||
RoomsQuery.Instance.EndTracking(); |
|||
GameObject.Destroy(m_updateSlowObj); |
|||
} |
|||
|
|||
private IEnumerator WaitForSignin() |
|||
{ |
|||
// Wait a reasonable amount of time for sign-in to complete.
|
|||
if (!m_didSigninComplete) |
|||
yield return new WaitForSeconds(3); |
|||
if (!m_didSigninComplete) |
|||
Assert.Fail("Did not sign in."); |
|||
} |
|||
|
|||
private IEnumerator CreateRoom(string roomName, string userId) |
|||
{ |
|||
Response<Room> createResponse = null; |
|||
float timeout = 5; |
|||
RoomsInterface.CreateRoomAsync(userId, roomName, 4, false, (r) => { createResponse = r; }); |
|||
while (createResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (room creation)."); |
|||
m_workingRoomId = createResponse.Result.Id; |
|||
} |
|||
|
|||
private IEnumerator PushPlayerData(LobbyUser player) |
|||
{ |
|||
bool hasPushedPlayerData = false; |
|||
float timeout = 5; |
|||
RoomsQuery.Instance.UpdatePlayerDataAsync(LobbyRelaySample.Lobby.ToLobbyData.RetrieveUserData(player), () => { hasPushedPlayerData = true; }); // RoomsContentHeartbeat normally does this.
|
|||
while (!hasPushedPlayerData && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (push player data)."); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// After creating a room and a player, signal that the player is Ready. This should lead to a countdown time being set for all players.
|
|||
/// </summary>
|
|||
[UnityTest] |
|||
public IEnumerator SetCountdownTimeSinglePlayer() |
|||
{ |
|||
LogAssert.ignoreFailingMessages = true; // Not sure why, but when auth logs in, it sometimes generates an error: "A Native Collection has not been disposed[...]." We don't want this to cause test failures, since in practice it *seems* to not negatively impact behavior.
|
|||
bool? readyResult = null; |
|||
LobbyReadyCheck readyCheck = new LobbyReadyCheck((b) => { readyResult = b; }, 5); // This ready time is used for the countdown target end, not for any of the timing of actually detecting readies.
|
|||
yield return WaitForSignin(); |
|||
|
|||
string userId = m_auth.GetSubIdentity(LobbyRelaySample.Auth.IIdentityType.Auth).GetContent("id"); |
|||
yield return CreateRoom("TestReadyRoom1", userId); |
|||
|
|||
RoomsQuery.Instance.BeginTracking(m_workingRoomId); |
|||
yield return new WaitForSeconds(2); // Allow the initial room retrieval.
|
|||
|
|||
LobbyUser user = new LobbyUser(); |
|||
user.ID = userId; |
|||
user.UserStatus = UserStatus.Ready; |
|||
yield return PushPlayerData(user); |
|||
|
|||
readyCheck.BeginCheckingForReady(); |
|||
float timeout = 5; // Long enough for two slow updates
|
|||
yield return new WaitForSeconds(timeout); |
|||
|
|||
readyCheck.Dispose(); |
|||
RoomsQuery.Instance.EndTracking(); |
|||
|
|||
yield return new WaitForSeconds(2); // Buffer to prevent a 429 on the upcoming Get, since there's a Get request on the slow upate loop when that's active.
|
|||
Response<Room> getResponse = null; |
|||
timeout = 5; |
|||
RoomsInterface.GetRoomAsync(m_workingRoomId, (r) => { getResponse = r; }); |
|||
while (getResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (get room)."); |
|||
Assert.NotNull(getResponse.Result, "Retrieved room successfully."); |
|||
Assert.NotNull(getResponse.Result.Data, "Room should have data."); |
|||
|
|||
Assert.True(getResponse.Result.Data.ContainsKey("AllPlayersReady"), "Check for AllPlayersReady key."); |
|||
string readyString = getResponse.Result.Data["AllPlayersReady"]?.Value; |
|||
Assert.NotNull(readyString, "Check for non-null AllPlayersReady."); |
|||
Assert.True(long.TryParse(readyString, out long ticks), "Check for ticks value in AllPlayersReady."); // This will be based on the current time, so we won't check for a specific value.
|
|||
} |
|||
|
|||
// Can't test with multiple players on one machine, since anonymous UAS credentials can't be manually supplied.
|
|||
} |
|||
} |
|
|||
using NUnit.Framework; |
|||
using System.Collections; |
|||
using System.Linq; |
|||
using Unity.Services.Rooms; |
|||
using Unity.Services.Rooms.Models; |
|||
using UnityEngine; |
|||
using UnityEngine.TestTools; |
|||
using RoomsInterface = LobbyRelaySample.Lobby.RoomsInterface; |
|||
|
|||
namespace Test |
|||
{ |
|||
/// <summary>
|
|||
/// Hits the Authentication and Rooms services in order to ensure rooms can be created and deleted.
|
|||
/// The actual code accessing rooms should go through RoomsQuery.
|
|||
/// </summary>
|
|||
public class RoomsRoundtripTests |
|||
{ |
|||
private string m_workingRoomId; |
|||
private LobbyRelaySample.Auth.SubIdentity_Authentication m_auth; |
|||
private bool m_didSigninComplete = false; |
|||
|
|||
[OneTimeSetUp] |
|||
public void Setup() |
|||
{ |
|||
m_auth = new LobbyRelaySample.Auth.SubIdentity_Authentication(() => { m_didSigninComplete = true; }); |
|||
} |
|||
|
|||
[UnityTearDown] |
|||
public IEnumerator PerTestTeardown() |
|||
{ |
|||
if (m_workingRoomId != null) |
|||
{ RoomsInterface.DeleteRoomAsync(m_workingRoomId, null); |
|||
m_workingRoomId = null; |
|||
} |
|||
yield return new WaitForSeconds(0.5f); // We need a yield anyway, so wait long enough to probably delete the room. There currently (6/22/2021) aren't other tests that would have issues if this took longer.
|
|||
} |
|||
|
|||
[OneTimeTearDown] |
|||
public void Teardown() |
|||
{ |
|||
m_auth?.Dispose(); |
|||
LogAssert.ignoreFailingMessages = false; |
|||
} |
|||
|
|||
[UnityTest] |
|||
public IEnumerator DoRoundtrip() |
|||
{ |
|||
LogAssert.ignoreFailingMessages = true; // Not sure why, but when auth logs in, it sometimes generates an error: "A Native Collection has not been disposed[...]." We don't want this to cause test failures, since in practice it *seems* to not negatively impact behavior.
|
|||
|
|||
// Wait a reasonable amount of time for sign-in to complete.
|
|||
if (!m_didSigninComplete) |
|||
yield return new WaitForSeconds(3); |
|||
if (!m_didSigninComplete) |
|||
Assert.Fail("Did not sign in."); |
|||
|
|||
// Since we're signed in through the same pathway as the actual game, the list of rooms will include any that have been made in the game itself, so we should account for those.
|
|||
// If you want to get around this, consider having a secondary project using the same assets with its own credentials.
|
|||
yield return new WaitForSeconds(1); // To prevent a possible 429 with the upcoming Query request, in case a previous test had one; Query requests can only occur at a rate of 1 per second.
|
|||
Response<QueryResponse> queryResponse = null; |
|||
float timeout = 5; |
|||
RoomsInterface.QueryAllRoomsAsync((qr) => { queryResponse = qr; }); |
|||
while (queryResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (query #0)"); |
|||
Assert.IsTrue(queryResponse.Status >= 200 && queryResponse.Status < 300, "QueryAllRoomsAsync should return a success code. (#0)"); |
|||
int numRoomsIni = queryResponse.Result.Results?.Count ?? 0; |
|||
|
|||
// Create a test room.
|
|||
Response<Room> createResponse = null; |
|||
timeout = 5; |
|||
string roomName = "TestRoom-JustATestRoom-123"; |
|||
RoomsInterface.CreateRoomAsync(m_auth.GetContent("id"), roomName, 100, false, (r) => { createResponse = r; }); |
|||
while (createResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (create)"); |
|||
Assert.IsTrue(createResponse.Status >= 200 && createResponse.Status < 300, "CreateRoomAsync should return a success code."); |
|||
m_workingRoomId = createResponse.Result.Id; |
|||
Assert.AreEqual(roomName, createResponse.Result.Name, "Created room should match the provided name."); |
|||
|
|||
// Query for the test room via QueryAllRooms.
|
|||
yield return new WaitForSeconds(1); // To prevent a possible 429 with the upcoming Query request.
|
|||
queryResponse = null; |
|||
timeout = 5; |
|||
RoomsInterface.QueryAllRoomsAsync((qr) => { queryResponse = qr; }); |
|||
while (queryResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (query #1)"); |
|||
Assert.IsTrue(queryResponse.Status >= 200 && queryResponse.Status < 300, "QueryAllRoomsAsync should return a success code. (#1)"); |
|||
Assert.AreEqual(1 + numRoomsIni, queryResponse.Result.Results.Count, "Queried rooms list should contain the test room."); |
|||
Assert.IsTrue(queryResponse.Result.Results.Where(r => r.Name == roomName).Count() == 1, "Checking queried room for name."); |
|||
Assert.IsTrue(queryResponse.Result.Results.Where(r => r.Id == m_workingRoomId).Count() == 1, "Checking queried room for ID."); |
|||
|
|||
// Query for solely the test room via GetRoom.
|
|||
Response<Room> getResponse = null; |
|||
timeout = 5; |
|||
RoomsInterface.GetRoomAsync(createResponse.Result.Id, (r) => { getResponse = r; }); |
|||
while (getResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (get)"); |
|||
Assert.IsTrue(getResponse.Status >= 200 && getResponse.Status < 300, "GetRoomAsync should return a success code."); |
|||
Assert.AreEqual(roomName, getResponse.Result.Name, "Checking the room we got for name."); |
|||
Assert.AreEqual(m_workingRoomId, getResponse.Result.Id, "Checking the room we got for ID."); |
|||
|
|||
// Delete the test room.
|
|||
Response deleteResponse = null; |
|||
timeout = 5; |
|||
RoomsInterface.DeleteRoomAsync(m_workingRoomId, (r) => { deleteResponse = r; }); |
|||
while (deleteResponse == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (delete)"); |
|||
Assert.IsTrue(deleteResponse.Status >= 200 && deleteResponse.Status < 300, "DeleteRoomAsync should return a success code."); |
|||
m_workingRoomId = null; |
|||
|
|||
// Query to ensure the room is gone.
|
|||
yield return new WaitForSeconds(1); // To prevent a possible 429 with the upcoming Query request.
|
|||
Response<QueryResponse> queryResponseTwo = null; |
|||
timeout = 5; |
|||
RoomsInterface.QueryAllRoomsAsync((qr) => { queryResponseTwo = qr; }); |
|||
while (queryResponseTwo == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check (query #2)"); |
|||
Assert.IsTrue(queryResponseTwo.Status >= 200 && queryResponseTwo.Status < 300, "QueryAllRoomsAsync should return a success code. (#2)"); |
|||
Assert.AreEqual(numRoomsIni, queryResponseTwo.Result.Results.Count, "Queried rooms list should be empty."); |
|||
|
|||
// Some error messages might be asynchronous, so to reduce spillover into other tests, just wait here for a bit before proceeding.
|
|||
yield return new WaitForSeconds(3); |
|||
LogAssert.ignoreFailingMessages = false; |
|||
} |
|||
|
|||
[UnityTest] |
|||
public IEnumerator OnCompletesOnFailure() |
|||
{ |
|||
LogAssert.ignoreFailingMessages = true; |
|||
if (!m_didSigninComplete) |
|||
yield return new WaitForSeconds(3); |
|||
if (!m_didSigninComplete) |
|||
Assert.Fail("Did not sign in."); |
|||
|
|||
bool? didComplete = null; |
|||
RoomsInterface.CreateRoomAsync("ThisStringIsInvalidHere", "room name", 123, false, (r) => { didComplete = (r == null); }); |
|||
float timeout = 5; |
|||
while (didComplete == null && timeout > 0) |
|||
{ yield return new WaitForSeconds(0.25f); |
|||
timeout -= 0.25f; |
|||
} |
|||
Assert.Greater(timeout, 0, "Timeout check"); |
|||
Assert.NotNull(didComplete, "Should have called onComplete, even if the async request failed."); |
|||
Assert.True(didComplete, "The returned object will be null, so expect to need to handle it."); |
|||
} |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 9a70bc1b6f999ee43974bbbf991a0b6a |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using UnityEngine; |
|||
using UnityEngine.Events; |
|||
|
|||
[System.Serializable] |
|||
public class StringEvent : UnityEvent<string> { } |
|
|||
fileFormatVersion: 2 |
|||
guid: 19bfe59f0f446ac4ea431b38580a52cf |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
public class LobbyStateVisibilityUI : ObserverPanel<LobbyData> |
|||
{ |
|||
[SerializeField] |
|||
private LobbyState m_ShowThisWhen; |
|||
|
|||
public override void ObservedUpdated(LobbyData observed) |
|||
{ |
|||
if (m_ShowThisWhen.HasFlag(observed.State)) |
|||
Show(); |
|||
else |
|||
Hide(); |
|||
} |
|||
} |
|||
} |
|||
|
|
|||
using System.Collections.Generic; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Watches for changes in the Lobby's player List
|
|||
/// </summary>
|
|||
[RequireComponent(typeof(LobbyDataObserver))] |
|||
public class LobbyUsersUI : ObserverPanel<LobbyData> |
|||
{ |
|||
[SerializeField] |
|||
List<LobbyUserCardUI> m_PlayerCardSlots = new List<LobbyUserCardUI>(); |
|||
List<string> m_CurrentUsers = new List<string>(); // Just for keeping track more easily of which users are already displayed.
|
|||
|
|||
/// <summary>
|
|||
/// When the observed data updates, we need to detect changes to the list of players.
|
|||
/// </summary>
|
|||
public override void ObservedUpdated(LobbyData observed) |
|||
{ |
|||
for (int id = m_CurrentUsers.Count - 1; id >= 0; id--) // We might remove users if they aren't in the new data, so iterate backwards.
|
|||
{ |
|||
string userId = m_CurrentUsers[id]; |
|||
if (!observed.LobbyUsers.ContainsKey(userId)) |
|||
{ |
|||
foreach (var card in m_PlayerCardSlots) |
|||
{ |
|||
if (card.UserId == userId) |
|||
{ |
|||
card.OnUserLeft(); |
|||
OnUserLeft(userId); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
|
|||
foreach (var lobbyUserKvp in observed.LobbyUsers) // If there are new players, we need to hook them into the UI.
|
|||
{ |
|||
if (m_CurrentUsers.Contains(lobbyUserKvp.Key)) |
|||
continue; |
|||
m_CurrentUsers.Add(lobbyUserKvp.Key); |
|||
|
|||
foreach (var pcu in m_PlayerCardSlots) |
|||
{ |
|||
if (pcu.IsAssigned) |
|||
continue; |
|||
pcu.SetUser(lobbyUserKvp.Value); |
|||
break; |
|||
} |
|||
} |
|||
} |
|||
|
|||
void OnUserLeft(string userID) |
|||
{ |
|||
if (!m_CurrentUsers.Contains(userID)) |
|||
return; |
|||
m_CurrentUsers.Remove(userID); |
|||
} |
|||
} |
|||
} |
|
|||
using TMPro; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Read Only input field (for copy/paste reasons) Watches for the changes in the lobby's Relay Code
|
|||
/// </summary>
|
|||
public class RelayCodeUI : ObserverPanel<LobbyData> |
|||
{ |
|||
[SerializeField] |
|||
TMP_InputField relayCodeText; |
|||
|
|||
public override void ObservedUpdated(LobbyData observed) |
|||
{ |
|||
if (!string.IsNullOrEmpty(observed.RelayCode)) |
|||
{ |
|||
relayCodeText.text = observed.RelayCode; |
|||
Show(); |
|||
} |
|||
else |
|||
{ |
|||
Hide(); |
|||
} |
|||
} |
|||
} |
|||
} |
|
|||
using TMPro; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Read Only input field (for copy/paste reasons) Watches for the changes in the lobby's Room Code
|
|||
/// </summary>
|
|||
public class RoomCodeUI : ObserverPanel<LobbyData> |
|||
{ |
|||
public TMP_InputField roomCodeText; |
|||
|
|||
public override void ObservedUpdated(LobbyData observed) |
|||
{ |
|||
if (!string.IsNullOrEmpty(observed.RoomCode)) |
|||
{ |
|||
roomCodeText.text = observed.RoomCode; |
|||
Show(); |
|||
} |
|||
else |
|||
{ |
|||
Hide(); |
|||
} |
|||
|
|||
} |
|||
} |
|||
} |
|
|||
using TMPro; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
public class ServerAddressUI : ObserverPanel<LobbyData> |
|||
{ |
|||
[SerializeField] |
|||
TMP_Text m_IPAddressText; |
|||
|
|||
public override void ObservedUpdated(LobbyData observed) |
|||
{ |
|||
m_IPAddressText.SetText(observed.RelayServer?.ToString()); |
|||
} |
|||
} |
|||
} |
|
|||
using TMPro; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
public class ServerNameUI : ObserverPanel<LobbyData> |
|||
{ |
|||
[SerializeField] |
|||
TMP_Text m_ServerNameText; |
|||
|
|||
public override void ObservedUpdated(LobbyData observed) |
|||
{ |
|||
m_ServerNameText.SetText(observed.LobbyName); |
|||
} |
|||
} |
|||
} |
|
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
public class StartLobbyButton : MonoBehaviour |
|||
{ |
|||
public void ToJoinMenu() |
|||
{ |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.ChangeGameState, GameState.JoinMenu); |
|||
} |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 4e59a0c0ec4227344bcc4a4f79c8ac31 |
|||
folderAsset: yes |
|||
DefaultImporter: |
|||
externalObjects: {} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
fileFormatVersion: 2 |
|||
guid: 0e7b1d59375bdf94795f339fd9395761 |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using System.Collections; |
|||
using System.Collections.Generic; |
|||
using UnityEngine; |
|||
|
|||
/// <summary>
|
|||
/// Temporary script to allow a user to delete all the rooms they've previously made, so we don't have orphaned empty rooms.
|
|||
/// </summary>
|
|||
public class TempDeleteAllRooms : MonoBehaviour |
|||
{ |
|||
private Queue<Unity.Services.Rooms.Models.Room> m_pendingRooms; |
|||
|
|||
public void OnButton() |
|||
{ |
|||
LobbyRelaySample.Lobby.RoomsInterface.QueryAllRoomsAsync((qr) => { DoDeletes(qr); }); |
|||
} |
|||
|
|||
private void DoDeletes(Unity.Services.Rooms.Response<Unity.Services.Rooms.Models.QueryResponse> response) |
|||
{ |
|||
if (response != null && response.Status >= 200 && response.Status < 300) |
|||
{ |
|||
StartCoroutine(DeleteCoroutine(response.Result.Results)); |
|||
} |
|||
} |
|||
|
|||
private IEnumerator DeleteCoroutine(List<Unity.Services.Rooms.Models.Room> rooms) |
|||
{ |
|||
foreach (var room in rooms) |
|||
{ |
|||
LobbyRelaySample.Lobby.RoomsInterface.DeleteRoomAsync(room.Id, null); // The onComplete callback isn't called in some error cases, e.g. a 403 when we don't have permissions, so don't block on it.
|
|||
yield return new WaitForSeconds(1); // We need to wait a little to avoid 429's, but we might not run an onComplete depending on how the delete call fails.
|
|||
} |
|||
} |
|||
} |
|
|||
{ |
|||
"templatePinStates": [], |
|||
"dependencyTypeInfos": [ |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.AnimationClip", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEditor.Animations.AnimatorController", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.AnimatorOverrideController", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEditor.Audio.AudioMixerController", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.ComputeShader", |
|||
"ignore": true, |
|||
"defaultInstantiationMode": 1, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Cubemap", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.GameObject", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEditor.LightingDataAsset", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": false |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.LightingSettings", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Material", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEditor.MonoScript", |
|||
"ignore": true, |
|||
"defaultInstantiationMode": 1, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.PhysicMaterial", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.PhysicsMaterial2D", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Rendering.PostProcessing.PostProcessProfile", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Rendering.PostProcessing.PostProcessResources", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Rendering.VolumeProfile", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEditor.SceneAsset", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": false |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Shader", |
|||
"ignore": true, |
|||
"defaultInstantiationMode": 1, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.ShaderVariantCollection", |
|||
"ignore": true, |
|||
"defaultInstantiationMode": 1, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Texture", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Texture2D", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
}, |
|||
{ |
|||
"userAdded": false, |
|||
"type": "UnityEngine.Timeline.TimelineAsset", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 0, |
|||
"supportsModification": true |
|||
} |
|||
], |
|||
"defaultDependencyTypeInfo": { |
|||
"userAdded": false, |
|||
"type": "<default_scene_template_dependencies>", |
|||
"ignore": false, |
|||
"defaultInstantiationMode": 1, |
|||
"supportsModification": true |
|||
}, |
|||
"newSceneOverride": 0 |
|||
} |
|
|||
{ |
|||
"MonoBehaviour": { |
|||
"Version": 3, |
|||
"EnableBurstCompilation": true, |
|||
"EnableOptimisations": true, |
|||
"EnableSafetyChecks": false, |
|||
"EnableDebugInAllBuilds": false, |
|||
"UsePlatformSDKLinker": false, |
|||
"CpuMinTargetX32": 0, |
|||
"CpuMaxTargetX32": 0, |
|||
"CpuMinTargetX64": 0, |
|||
"CpuMaxTargetX64": 0, |
|||
"CpuTargetsX32": 6, |
|||
"CpuTargetsX64": 72 |
|||
} |
|||
} |
|
|||
{ |
|||
"MonoBehaviour": { |
|||
"Version": 3, |
|||
"DisabledWarnings": "" |
|||
} |
|||
} |
部分文件因为文件数量过多而无法显示
撰写
预览
正在加载...
取消
保存
Reference in new issue