m_Lobby = await Lobbies.Instance.CreateLobbyAsync(lobbyName, maxPlayers, options);var callbacks = new LobbyEventCallbacks();callbacks.LobbyChanged += OnLobbyChanged;callbacks.KickedFromLobby += OnKickedFromLobby;callbacks.LobbyEventConnectionStateChanged += OnLobbyEventConnectionStateChanged;try { m_LobbyEvents = await Lobbies.Instance.SubscribeToLobbyEventsAsync(m_Lobby.Id, callbacks);}catch (LobbyServiceException ex){ switch (ex.Reason) { case LobbyExceptionReason.AlreadySubscribedToLobby: Debug.LogWarning($"Already subscribed to lobby[{m_Lobby.Id}]. We did not need to try and subscribe again. Exception Message: {ex.Message}"); break; case LobbyExceptionReason.SubscriptionToLobbyLostWhileBusy: Debug.LogError($"Subscription to lobby events was lost while it was busy trying to subscribe. Exception Message: {ex.Message}"); throw; case LobbyExceptionReason.LobbyEventServiceConnectionError: Debug.LogError($"Failed to connect to lobby events. Exception Message: {ex.Message}"); throw; default: throw; }}
注
ノート: 前のコードサンプルでは、
OnLobbyChanged
、
OnKickedFromLobby
、
OnLobbyEventConnectionStateChanged
がイベントを処理します。
以下のコードサンプルは、
OnLobbyChanged
のハンドラーの例を提供します。削除されたロビーインスタンスの処理方法を示しています。
private void OnLobbyChanged(ILobbyChanges changes){ if (changes.LobbyDeleted) { // Handle lobby being deleted // Calling changes.ApplyToLobby will log a warning and do nothing } else { changes.ApplyToLobby(m_Lobby); } // Refresh the UI in some way}
private void OnKickedFromLobby(){ // These events will never trigger again, so let’s remove it. this.m_LobbyEvents = null; // Refresh the UI in some way}
private void OnLobbyEventConnectionStateChanged(LobbyEventConnectionState state){ switch (state) { case LobbyEventConnectionState.Unsubscribed: /* Update the UI if necessary, as the subscription has been stopped. */ break; case LobbyEventConnectionState.Subscribing: /* Update the UI if necessary, while waiting to be subscribed. */ break; case LobbyEventConnectionState.Subscribed: /* Update the UI if necessary, to show subscription is working. */ break; case LobbyEventConnectionState.Unsynced: /* Update the UI to show connection problems. Lobby will attempt to reconnect automatically. */ break; case LobbyEventConnectionState.Error: /* Update the UI to show the connection has errored. Lobby will not attempt to reconnect as something has gone wrong. */ }}
private void OnLobbyChanged(ILobbyChanges changes){ changes.ApplyToLobby(m_Lobby); if (changes.Name.Changed) { // Do something specific due to this change } // Refresh the UI in some way}
API は、オプションでロビーのバージョンを引数として受け入れることができます。帯域幅を節約するために、ロビーは指定されたバージョンが現在のバージョンと一致しない場合にのみ返されます。以下のサンプルは、この例を示しています。
var lobby = await Lobbies.Instance.GetLobbyAsync("lobbyId");var version = lobby.Version;// check if a newer version of the lobby is available:var newLobby = await Lobbies.Instance.GetLobbyAsync("lobbyId", version);if (newLobby != null){ // New lobby version received version = lobby.Version; // observe changed values in newLobby:}