浏览代码
Merge pull request #9 from Unity-Technologies/master-lobby_merge_resolution-beta_packages_included-public_release_staging
Merge pull request #9 from Unity-Technologies/master-lobby_merge_resolution-beta_packages_included-public_release_staging
Public Release Structure/main
GitHub
4 年前
当前提交
0aa138ef
共有 37 个文件被更改,包括 2042 次插入 和 2132 次删除
-
6Assets/Prefabs/UI/LobbyButtonUI.prefab
-
3Assets/Prefabs/UI/LobbyCodeCanvas.prefab
-
140Assets/Scripts/Auth/NameGenerator.cs
-
6Assets/Scripts/Entities/GameStateManager.cs
-
542Assets/Scripts/Entities/LocalLobby.cs
-
8Assets/Scripts/Entities/LocalLobbyObserver.cs
-
200Assets/Scripts/Infrastructure/Locator.cs
-
126Assets/Scripts/Infrastructure/LogHandler.cs
-
176Assets/Scripts/Infrastructure/Messenger.cs
-
276Assets/Scripts/Infrastructure/UpdateSlow.cs
-
218Assets/Scripts/Lobby/LobbyAPIInterface.cs
-
439Assets/Scripts/Lobby/LobbyAsyncRequests.cs
-
218Assets/Scripts/Lobby/LobbyContentHeartbeat.cs
-
46Assets/Scripts/Lobby/LobbyListHeartbeat.cs
-
126Assets/Scripts/Lobby/ReadyCheck.cs
-
178Assets/Scripts/Lobby/ToLocalLobby.cs
-
4Assets/Scripts/LobbyRelaySample.asmdef
-
260Assets/Scripts/Tests/PlayMode/LobbyReadyCheckTests.cs
-
326Assets/Scripts/Tests/PlayMode/LobbyRoundtripTests.cs
-
2Assets/Scripts/Tests/PlayMode/Tests.Play.asmdef
-
40Assets/Scripts/UI/CountdownUI.cs
-
66Assets/Scripts/UI/DisplayCodeUI.cs
-
30Assets/Scripts/UI/EndGameButtonUI.cs
-
30Assets/Scripts/UI/ExitButtonUI.cs
-
120Assets/Scripts/UI/InLobbyUserList.cs
-
138Assets/Scripts/UI/InLobbyUserUI.cs
-
42Assets/Scripts/UI/JoinCreateLobbyUI.cs
-
38Assets/Scripts/UI/LobbyNameUI.cs
-
46Assets/Scripts/UI/ReadyCheckUI.cs
-
38Assets/Scripts/UI/RelayAddressUI.cs
-
4Assets/Scripts/UI/ShowWhenLobbyStateUI.cs
-
106Assets/Scripts/UI/SpinnerUI.cs
-
30Assets/Scripts/UI/StartLobbyButtonUI.cs
-
22Packages/manifest.json
-
57Packages/packages-lock.json
-
24ProjectSettings/PackageManagerSettings.asset
-
43README.md
|
|||
using System; |
|||
using System.Text; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Just for fun, give a cute default player name if no name is provided.
|
|||
/// </summary>
|
|||
public static class NameGenerator |
|||
{ |
|||
public static string GetName(string userId) |
|||
{ |
|||
int seed = userId.GetHashCode(); |
|||
seed *= Math.Sign(seed); |
|||
StringBuilder nameOutput = new StringBuilder(); |
|||
#region Word part
|
|||
int word = seed % 22; |
|||
if (word == 0) // Note that some more data-driven approach would be better.
|
|||
nameOutput.Append("Ant"); |
|||
else if (word == 1) |
|||
nameOutput.Append("Bear"); |
|||
else if (word == 2) |
|||
nameOutput.Append("Cow"); |
|||
else if (word == 3) |
|||
nameOutput.Append("Dog"); |
|||
else if (word == 4) |
|||
nameOutput.Append("Eel"); |
|||
else if (word == 5) |
|||
nameOutput.Append("Frog"); |
|||
else if (word == 6) |
|||
nameOutput.Append("Gopher"); |
|||
else if (word == 7) |
|||
nameOutput.Append("Heron"); |
|||
else if (word == 8) |
|||
nameOutput.Append("Ibex"); |
|||
else if (word == 9) |
|||
nameOutput.Append("Jerboa"); |
|||
else if (word == 10) |
|||
nameOutput.Append("Koala"); |
|||
else if (word == 11) |
|||
nameOutput.Append("Llama"); |
|||
else if (word == 12) |
|||
nameOutput.Append("Moth"); |
|||
else if (word == 13) |
|||
nameOutput.Append("Newt"); |
|||
else if (word == 14) |
|||
nameOutput.Append("Owl"); |
|||
else if (word == 15) |
|||
nameOutput.Append("Puffin"); |
|||
else if (word == 16) |
|||
nameOutput.Append("Raven"); |
|||
else if (word == 17) |
|||
nameOutput.Append("Snake"); |
|||
else if (word == 18) |
|||
nameOutput.Append("Trout"); |
|||
else if (word == 19) |
|||
nameOutput.Append("Vulture"); |
|||
else if (word == 20) |
|||
nameOutput.Append("Wolf"); |
|||
else |
|||
nameOutput.Append("Zebra"); |
|||
#endregion
|
|||
|
|||
int number = seed % 1000; |
|||
nameOutput.Append(number.ToString("000")); |
|||
|
|||
return nameOutput.ToString(); |
|||
} |
|||
} |
|||
} |
|||
using System; |
|||
using System.Text; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Just for fun, give a cute default player name if no name is provided.
|
|||
/// </summary>
|
|||
public static class NameGenerator |
|||
{ |
|||
public static string GetName(string userId) |
|||
{ |
|||
int seed = userId.GetHashCode(); |
|||
seed *= Math.Sign(seed); |
|||
StringBuilder nameOutput = new StringBuilder(); |
|||
#region Word part
|
|||
int word = seed % 22; |
|||
if (word == 0) // Note that some more data-driven approach would be better.
|
|||
nameOutput.Append("Ant"); |
|||
else if (word == 1) |
|||
nameOutput.Append("Bear"); |
|||
else if (word == 2) |
|||
nameOutput.Append("Cow"); |
|||
else if (word == 3) |
|||
nameOutput.Append("Dog"); |
|||
else if (word == 4) |
|||
nameOutput.Append("Eel"); |
|||
else if (word == 5) |
|||
nameOutput.Append("Frog"); |
|||
else if (word == 6) |
|||
nameOutput.Append("Gopher"); |
|||
else if (word == 7) |
|||
nameOutput.Append("Heron"); |
|||
else if (word == 8) |
|||
nameOutput.Append("Ibex"); |
|||
else if (word == 9) |
|||
nameOutput.Append("Jerboa"); |
|||
else if (word == 10) |
|||
nameOutput.Append("Koala"); |
|||
else if (word == 11) |
|||
nameOutput.Append("Llama"); |
|||
else if (word == 12) |
|||
nameOutput.Append("Moth"); |
|||
else if (word == 13) |
|||
nameOutput.Append("Newt"); |
|||
else if (word == 14) |
|||
nameOutput.Append("Owl"); |
|||
else if (word == 15) |
|||
nameOutput.Append("Puffin"); |
|||
else if (word == 16) |
|||
nameOutput.Append("Raven"); |
|||
else if (word == 17) |
|||
nameOutput.Append("Snake"); |
|||
else if (word == 18) |
|||
nameOutput.Append("Trout"); |
|||
else if (word == 19) |
|||
nameOutput.Append("Vulture"); |
|||
else if (word == 20) |
|||
nameOutput.Append("Wolf"); |
|||
else |
|||
nameOutput.Append("Zebra"); |
|||
#endregion
|
|||
|
|||
int number = seed % 1000; |
|||
nameOutput.Append(number.ToString("000")); |
|||
|
|||
return nameOutput.ToString(); |
|||
} |
|||
} |
|||
} |
|
|||
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); |
|||
} |
|||
} |
|||
} |
|||
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 |
|||
{ |
|||
public class LocalLobbyObserver : ObserverBehaviour<LocalLobby> { } |
|||
} |
|||
namespace LobbyRelaySample |
|||
{ |
|||
public class LocalLobbyObserver : ObserverBehaviour<LocalLobby> { } |
|||
} |
|
|||
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, so that verbose logs (both from the services and from any of our Debug.Log* calls) don't clutter the Console.
|
|||
/// </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, |
|||
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 |
|||
{ |
|||
/// <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 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); |
|||
} |
|||
} |
|||
} |
|||
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); |
|||
} |
|||
} |
|||
} |
|
|||
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 System; |
|||
using System.Collections.Generic; |
|||
using System.Threading.Tasks; |
|||
using Unity.Services.Lobbies; |
|||
using Unity.Services.Lobbies.Models; |
|||
|
|||
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<Lobby>> onComplete) |
|||
{ |
|||
CreateLobbyRequest createRequest = new CreateLobbyRequest(new CreateRequest( |
|||
name: lobbyName, |
|||
player: new Player(requesterUASId), |
|||
maxPlayers: maxPlayers, |
|||
isPrivate: isPrivate |
|||
)); |
|||
var task = LobbyService.LobbyApiClient.CreateLobbyAsync(createRequest); |
|||
new InProgressRequest<Response<Lobby>>(task, onComplete); |
|||
} |
|||
|
|||
public static void DeleteLobbyAsync(string lobbyId, Action<Response> onComplete) |
|||
{ |
|||
DeleteLobbyRequest deleteRequest = new DeleteLobbyRequest(lobbyId); |
|||
var task = LobbyService.LobbyApiClient.DeleteLobbyAsync(deleteRequest); |
|||
new InProgressRequest<Response>(task, onComplete); |
|||
} |
|||
|
|||
public static void JoinLobbyAsync_ByCode(string requesterUASId, string lobbyCode, Action<Response<Lobby>> onComplete) |
|||
{ |
|||
JoinLobbyByCodeRequest joinRequest = new JoinLobbyByCodeRequest(new JoinByCodeRequest(lobbyCode, new Player(requesterUASId))); |
|||
var task = LobbyService.LobbyApiClient.JoinLobbyByCodeAsync(joinRequest); |
|||
new InProgressRequest<Response<Lobby>>(task, onComplete); |
|||
} |
|||
|
|||
public static void JoinLobbyAsync_ById(string requesterUASId, string lobbyId, Action<Response<Lobby>> onComplete) |
|||
{ |
|||
JoinLobbyByIdRequest joinRequest = new JoinLobbyByIdRequest(lobbyId, new Player(requesterUASId)); |
|||
var task = LobbyService.LobbyApiClient.JoinLobbyByIdAsync(joinRequest); |
|||
new InProgressRequest<Response<Lobby>>(task, onComplete); |
|||
} |
|||
|
|||
public static void LeaveLobbyAsync(string requesterUASId, string lobbyId, Action<Response> onComplete) |
|||
{ |
|||
RemovePlayerRequest leaveRequest = new RemovePlayerRequest(lobbyId, requesterUASId); |
|||
var task = LobbyService.LobbyApiClient.RemovePlayerAsync(leaveRequest); |
|||
new InProgressRequest<Response>(task, onComplete); |
|||
} |
|||
|
|||
public static void QueryAllLobbiesAsync(Action<Response<QueryResponse>> onComplete) |
|||
{ |
|||
QueryLobbiesRequest queryRequest = new QueryLobbiesRequest(new QueryRequest(count: k_maxLobbiesToShow)); |
|||
var task = LobbyService.LobbyApiClient.QueryLobbiesAsync(queryRequest); |
|||
new InProgressRequest<Response<QueryResponse>>(task, onComplete); |
|||
} |
|||
|
|||
public static void GetLobbyAsync(string lobbyId, Action<Response<Lobby>> onComplete) |
|||
{ |
|||
GetLobbyRequest getRequest = new GetLobbyRequest(lobbyId); |
|||
var task = LobbyService.LobbyApiClient.GetLobbyAsync(getRequest); |
|||
new InProgressRequest<Response<Lobby>>(task, onComplete); |
|||
} |
|||
|
|||
public static void UpdateLobbyAsync(string lobbyId, Dictionary<string, DataObject> data, Action<Response<Lobby>> onComplete) |
|||
{ |
|||
UpdateLobbyRequest updateRequest = new UpdateLobbyRequest(lobbyId, new UpdateRequest( |
|||
data: data |
|||
)); |
|||
var task = LobbyService.LobbyApiClient.UpdateLobbyAsync(updateRequest); |
|||
new InProgressRequest<Response<Lobby>>(task, onComplete); |
|||
} |
|||
|
|||
public static void UpdatePlayerAsync(string lobbyId, string playerId, Dictionary<string, PlayerDataObject> data, Action<Response<Lobby>> onComplete) |
|||
{ |
|||
UpdatePlayerRequest updateRequest = new UpdatePlayerRequest(lobbyId, playerId, new PlayerUpdateRequest( |
|||
data: data |
|||
)); |
|||
var task = LobbyService.LobbyApiClient.UpdatePlayerAsync(updateRequest); |
|||
new InProgressRequest<Response<Lobby>>(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 LobbyRelaySample.lobby; |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using Unity.Services.Authentication; |
|||
using Unity.Services.Lobbies; |
|||
using Unity.Services.Lobbies.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 Lobby m_lastKnownLobby; |
|||
private bool m_isMidRetrieve = false; |
|||
public Lobby 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(Lobby 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<Lobby> onSuccess, Action onFailure) |
|||
{ |
|||
string uasId = AuthenticationService.Instance.PlayerId; |
|||
LobbyAPIInterface.CreateLobbyAsync(uasId, lobbyName, maxPlayers, isPrivate, OnLobbyCreated); |
|||
|
|||
void OnLobbyCreated(Response<Lobby> 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<Lobby> onSuccess, Action onFailure) |
|||
{ |
|||
string uasId = AuthenticationService.Instance.PlayerId; |
|||
if (!string.IsNullOrEmpty(lobbyId)) |
|||
LobbyAPIInterface.JoinLobbyAsync_ById(uasId, lobbyId, OnLobbyJoined); |
|||
else |
|||
LobbyAPIInterface.JoinLobbyAsync_ByCode(uasId, lobbyCode, OnLobbyJoined); |
|||
|
|||
void OnLobbyJoined(Response<Lobby> 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<Lobby> 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<Lobby> 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; |
|||
|
|||
Lobby 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; |
|||
|
|||
Lobby 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; |
|||
} |
|||
Lobby 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 System; |
|||
using LobbyRemote = Unity.Services.Lobbies.Models.Lobby; |
|||
|
|||
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 lobbyRemote = LobbyAsyncRequests.Instance.CurrentLobby; |
|||
if (lobbyRemote == null) return; |
|||
bool prevShouldPush = m_shouldPushData; |
|||
var prevState = m_localLobby.State; |
|||
lobby.ToLocalLobby.Convert(lobbyRemote, 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 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; |
|||
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; |
|||
} |
|||
} |
|||
} |
|||
using System.Collections.Generic; |
|||
using Unity.Services.Lobbies.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(Lobby lobby, LocalLobby outputToHere, LobbyUser existingLocalUser = null) |
|||
{ |
|||
LobbyInfo info = new LobbyInfo |
|||
{ LobbyID = lobby.Id, |
|||
LobbyCode = lobby.LobbyCode, |
|||
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(Lobby 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; |
|||
} |
|||
} |
|||
} |
|
|||
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 LobbyRelaySample; |
|||
using NUnit.Framework; |
|||
using System.Collections; |
|||
using Unity.Services.Lobbies; |
|||
using Unity.Services.Lobbies.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<Lobby> 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<Lobby> 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 NUnit.Framework; |
|||
using System.Collections; |
|||
using System.Linq; |
|||
using Unity.Services.Lobbies; |
|||
using Unity.Services.Lobbies.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<Lobby> 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<Lobby> 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>
|
|||
/// After all players ready up for the game, this will show the countdown that occurs.
|
|||
/// </summary>
|
|||
public class CountdownUI : ObserverPanel<LocalLobby> |
|||
{ |
|||
[SerializeField] |
|||
TMP_Text m_CountDownText; |
|||
|
|||
public override void ObservedUpdated(LocalLobby observed) |
|||
{ |
|||
if (observed.CountDownTime <= 0) |
|||
return; |
|||
m_CountDownText.SetText($"Starting in: {observed.CountDownTime}"); |
|||
} |
|||
} |
|||
using TMPro; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// After all players ready up for the game, this will show the countdown that occurs.
|
|||
/// </summary>
|
|||
public class CountdownUI : ObserverPanel<LocalLobby> |
|||
{ |
|||
[SerializeField] |
|||
TMP_Text m_CountDownText; |
|||
|
|||
public override void ObservedUpdated(LocalLobby observed) |
|||
{ |
|||
if (observed.CountDownTime <= 0) |
|||
return; |
|||
m_CountDownText.SetText($"Starting in: {observed.CountDownTime}"); |
|||
} |
|||
} |
|||
} |
|
|||
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 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 UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// After connecting to Relay, the host can use this to end the game, returning to the regular lobby state.
|
|||
/// </summary>
|
|||
public class EndGameButtonUI : MonoBehaviour |
|||
{ |
|||
public void EndGame() |
|||
{ |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.ToLobby, null); |
|||
} |
|||
} |
|||
} |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// After connecting to Relay, the host can use this to end the game, returning to the regular lobby state.
|
|||
/// </summary>
|
|||
public class EndGameButtonUI : MonoBehaviour |
|||
{ |
|||
public void EndGame() |
|||
{ |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.ToLobby, null); |
|||
} |
|||
} |
|||
} |
|
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// When the main menu's Exit button is selected, send a quit signal.
|
|||
/// </summary>
|
|||
public class ExitButtonUI : MonoBehaviour |
|||
{ |
|||
public void OnExitButton() |
|||
{ |
|||
Application.Quit(); |
|||
} |
|||
} |
|||
} |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// When the main menu's Exit button is selected, send a quit signal.
|
|||
/// </summary>
|
|||
public class ExitButtonUI : MonoBehaviour |
|||
{ |
|||
public void OnExitButton() |
|||
{ |
|||
Application.Quit(); |
|||
} |
|||
} |
|||
} |
|
|||
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 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>
|
|||
/// When inside a lobby, this will show information about a player, whether local or remote.
|
|||
/// </summary>
|
|||
[RequireComponent(typeof(LobbyUserObserver))] |
|||
public class InLobbyUserUI : ObserverPanel<LobbyUser> |
|||
{ |
|||
[SerializeField] |
|||
TMP_Text m_DisplayNameText; |
|||
|
|||
[SerializeField] |
|||
TMP_Text m_StatusText; |
|||
|
|||
[SerializeField] |
|||
TMP_Text m_EmoteText; |
|||
|
|||
public bool IsAssigned |
|||
{ |
|||
get { return UserId != null; } |
|||
} |
|||
|
|||
public string UserId { get; private set; } |
|||
private LobbyUserObserver m_observer; |
|||
|
|||
public void SetUser(LobbyUser myLobbyUser) |
|||
{ |
|||
Show(); |
|||
if (m_observer == null) |
|||
m_observer = GetComponent<LobbyUserObserver>(); |
|||
m_observer.BeginObserving(myLobbyUser); |
|||
UserId = myLobbyUser.ID; |
|||
} |
|||
|
|||
public void OnUserLeft() |
|||
{ |
|||
UserId = null; |
|||
Hide(); |
|||
m_observer.EndObserving(); |
|||
} |
|||
|
|||
public override void ObservedUpdated(LobbyUser observed) |
|||
{ |
|||
m_DisplayNameText.SetText(observed.DisplayName); |
|||
m_StatusText.SetText(SetStatusFancy(observed.UserStatus)); |
|||
m_EmoteText.SetText(observed.Emote); |
|||
} |
|||
|
|||
string SetStatusFancy(UserStatus status) |
|||
{ |
|||
switch (status) |
|||
{ |
|||
case UserStatus.Lobby: |
|||
return "<color=#56B4E9>Lobby.</color>"; // Light Blue
|
|||
case UserStatus.Ready: |
|||
return "<color=#009E73>Ready!</color>"; // Light Mint
|
|||
case UserStatus.Connecting: |
|||
return "<color=#F0E442>Connecting.</color>"; // Bright Yellow
|
|||
case UserStatus.Connected: |
|||
return "<color=#005500>Connected.</color>"; //Orange
|
|||
default: |
|||
return "<color=#56B4E9>In Lobby.</color>"; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
using TMPro; |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// When inside a lobby, this will show information about a player, whether local or remote.
|
|||
/// </summary>
|
|||
[RequireComponent(typeof(LobbyUserObserver))] |
|||
public class InLobbyUserUI : ObserverPanel<LobbyUser> |
|||
{ |
|||
[SerializeField] |
|||
TMP_Text m_DisplayNameText; |
|||
|
|||
[SerializeField] |
|||
TMP_Text m_StatusText; |
|||
|
|||
[SerializeField] |
|||
TMP_Text m_EmoteText; |
|||
|
|||
public bool IsAssigned |
|||
{ |
|||
get { return UserId != null; } |
|||
} |
|||
|
|||
public string UserId { get; private set; } |
|||
private LobbyUserObserver m_observer; |
|||
|
|||
public void SetUser(LobbyUser myLobbyUser) |
|||
{ |
|||
Show(); |
|||
if (m_observer == null) |
|||
m_observer = GetComponent<LobbyUserObserver>(); |
|||
m_observer.BeginObserving(myLobbyUser); |
|||
UserId = myLobbyUser.ID; |
|||
} |
|||
|
|||
public void OnUserLeft() |
|||
{ |
|||
UserId = null; |
|||
Hide(); |
|||
m_observer.EndObserving(); |
|||
} |
|||
|
|||
public override void ObservedUpdated(LobbyUser observed) |
|||
{ |
|||
m_DisplayNameText.SetText(observed.DisplayName); |
|||
m_StatusText.SetText(SetStatusFancy(observed.UserStatus)); |
|||
m_EmoteText.SetText(observed.Emote); |
|||
} |
|||
|
|||
string SetStatusFancy(UserStatus status) |
|||
{ |
|||
switch (status) |
|||
{ |
|||
case UserStatus.Lobby: |
|||
return "<color=#56B4E9>Lobby.</color>"; // Light Blue
|
|||
case UserStatus.Ready: |
|||
return "<color=#009E73>Ready!</color>"; // Light Mint
|
|||
case UserStatus.Connecting: |
|||
return "<color=#F0E442>Connecting.</color>"; // Bright Yellow
|
|||
case UserStatus.Connected: |
|||
return "<color=#005500>Connected.</color>"; //Orange
|
|||
default: |
|||
return "<color=#56B4E9>In Lobby.</color>"; |
|||
} |
|||
} |
|||
} |
|||
} |
|
|||
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(); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
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(); |
|||
} |
|||
} |
|||
} |
|||
} |
|
|||
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 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 UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Button callbacks for the "Ready"/"Not Ready" buttons used to indicate the local player is ready/not ready.
|
|||
/// </summary>
|
|||
public class ReadyCheckUI : MonoBehaviour |
|||
{ |
|||
public void OnReadyButton() |
|||
{ |
|||
ChangeState(UserStatus.Ready); |
|||
} |
|||
public void OnCancelButton() |
|||
{ |
|||
ChangeState(UserStatus.Lobby); |
|||
} |
|||
private void ChangeState(UserStatus status) |
|||
{ |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.ChangeLobbyUserState, status); |
|||
} |
|||
} |
|||
} |
|||
using UnityEngine; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Button callbacks for the "Ready"/"Not Ready" buttons used to indicate the local player is ready/not ready.
|
|||
/// </summary>
|
|||
public class ReadyCheckUI : MonoBehaviour |
|||
{ |
|||
public void OnReadyButton() |
|||
{ |
|||
ChangeState(UserStatus.Ready); |
|||
} |
|||
public void OnCancelButton() |
|||
{ |
|||
ChangeState(UserStatus.Lobby); |
|||
} |
|||
private void ChangeState(UserStatus status) |
|||
{ |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.ChangeLobbyUserState, status); |
|||
} |
|||
} |
|||
} |
|
|||
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 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 System.Text; |
|||
using TMPro; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Controls a simple throbber that is displayed when the lobby list is being refreshed.
|
|||
/// </summary>
|
|||
public class SpinnerUI : ObserverPanel<LobbyServiceData> |
|||
{ |
|||
public TMP_Text errorText; |
|||
public UIPanelBase spinnerImage; |
|||
public UIPanelBase noServerText; |
|||
public UIPanelBase errorTextVisibility; |
|||
|
|||
public override void ObservedUpdated(LobbyServiceData observed) |
|||
{ |
|||
if (observed.State == LobbyServiceState.Fetching) |
|||
{ |
|||
Show(); |
|||
spinnerImage.Show(); |
|||
noServerText.Hide(); |
|||
errorTextVisibility.Hide(); |
|||
} |
|||
else if (observed.State == LobbyServiceState.Error) |
|||
{ |
|||
spinnerImage.Hide(); |
|||
errorTextVisibility.Show(); |
|||
var errorString = new StringBuilder(); |
|||
errorString.Append("Error"); |
|||
var codeString = ": " + observed.lastErrorCode; |
|||
if (observed.lastErrorCode < 1) |
|||
codeString = "."; |
|||
|
|||
errorString.Append(codeString); |
|||
errorText.SetText(errorString.ToString()); |
|||
} |
|||
else if (observed.State == LobbyServiceState.Fetched) |
|||
{ |
|||
if (observed.CurrentLobbies.Count < 1) |
|||
{ |
|||
noServerText.Show(); |
|||
} |
|||
else |
|||
{ |
|||
noServerText.Hide(); |
|||
} |
|||
|
|||
spinnerImage.Hide(); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
using System.Text; |
|||
using TMPro; |
|||
|
|||
namespace LobbyRelaySample.UI |
|||
{ |
|||
/// <summary>
|
|||
/// Controls a simple throbber that is displayed when the lobby list is being refreshed.
|
|||
/// </summary>
|
|||
public class SpinnerUI : ObserverPanel<LobbyServiceData> |
|||
{ |
|||
public TMP_Text errorText; |
|||
public UIPanelBase spinnerImage; |
|||
public UIPanelBase noServerText; |
|||
public UIPanelBase errorTextVisibility; |
|||
|
|||
public override void ObservedUpdated(LobbyServiceData observed) |
|||
{ |
|||
if (observed.State == LobbyServiceState.Fetching) |
|||
{ |
|||
Show(); |
|||
spinnerImage.Show(); |
|||
noServerText.Hide(); |
|||
errorTextVisibility.Hide(); |
|||
} |
|||
else if (observed.State == LobbyServiceState.Error) |
|||
{ |
|||
spinnerImage.Hide(); |
|||
errorTextVisibility.Show(); |
|||
var errorString = new StringBuilder(); |
|||
errorString.Append("Error"); |
|||
var codeString = ": " + observed.lastErrorCode; |
|||
if (observed.lastErrorCode < 1) |
|||
codeString = "."; |
|||
|
|||
errorString.Append(codeString); |
|||
errorText.SetText(errorString.ToString()); |
|||
} |
|||
else if (observed.State == LobbyServiceState.Fetched) |
|||
{ |
|||
if (observed.CurrentLobbies.Count < 1) |
|||
{ |
|||
noServerText.Show(); |
|||
} |
|||
else |
|||
{ |
|||
noServerText.Hide(); |
|||
} |
|||
|
|||
spinnerImage.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 UnityEngine; |
|||
|
|||
namespace LobbyRelaySample |
|||
{ |
|||
/// <summary>
|
|||
/// Main menu start button.
|
|||
/// </summary>
|
|||
public class StartLobbyButtonUI : MonoBehaviour |
|||
{ |
|||
public void ToJoinMenu() |
|||
{ |
|||
Locator.Get.Messenger.OnReceiveMessage(MessageType.ChangeGameState, GameState.JoinMenu); |
|||
} |
|||
} |
|||
} |
撰写
预览
正在加载...
取消
保存
Reference in new issue