当玩家按离开大厅的按钮离开时,他就会从大厅中移除,新玩家可以加入。但是当玩家使用 alt f4 离开时,大厅仍然认为大厅已满。我该如何解决这个问题?
服务器可以看到玩家何时断开连接,并且我正在尝试删除该玩家。
public void StartHost()
{
NetworkManager.Singleton.ConnectionApprovalCallback += NetworkManager_ConnectionApprovalCallback;
NetworkManager.Singleton.OnClientDisconnectCallback += NetworkManager_Server_OnClientDisconnectCallback; ;
NetworkManager.Singleton.StartHost();
}
private void NetworkManager_Server_OnClientDisconnectCallback(ulong clientId)
{
if (IsServer)
{
// Log the disconnection
Debug.Log($"ONMUILTIPLAYERMANAGER Client {clientId} disconnected.");
// Update the lobby by removing the player
GameLobby.Instance?.DisconnectPlayer(clientId.ToString());
// Optionally handle any cleanup like respawning or managing game state.
}
}
private void NetworkManager_ConnectionApprovalCallback(NetworkManager.ConnectionApprovalRequest connectionApprovalRequest, NetworkManager.ConnectionApprovalResponse connectionApprovalResponse)
{
connectionApprovalResponse.Approved = true;
}
我也尝试过更新大厅插槽,但没有任何效果。
public async void DisconnectPlayer(string playerId)
{
try
{
if (joinedLobby != null)
{
// First, check if the player exists in the lobby
var player = joinedLobby.Players.Find(p => p.Id == playerId);
if (player != null)
{
// Attempt to remove the player from the lobby
await LobbyService.Instance.RemovePlayerAsync(joinedLobby.Id, playerId);
Debug.Log($"Player {playerId} successfully removed from lobby.");
}
else
{
Debug.Log($"Player {playerId} not found in the lobby.");
}
// Force update the lobby slots after the player leaves
await UpdateLobbySlots();
// Optionally, refresh the lobby state
joinedLobby = await LobbyService.Instance.GetLobbyAsync(joinedLobby.Id);
Debug.Log("Lobby slots updated after player disconnection.");
}
}
catch (LobbyServiceException e)
{
Debug.LogError($"Failed to remove player {playerId}: {e.Message}");
}
}
private async Task UpdateLobbySlots()
{
try
{
// Force update lobby data to reflect the correct available slots
await LobbyService.Instance.UpdateLobbyAsync(joinedLobby.Id, new UpdateLobbyOptions
{
Data = new Dictionary<string, DataObject>
{
{ "availableSlots", new DataObject(DataObject.VisibilityOptions.Public, (MultiplayerManager.MAX_PLAYER_AMOUNT - joinedLobby.Players.Count).ToString()) }
}
});
Debug.Log("Lobby slots successfully updated.");
Debug.Log(joinedLobby.Players.Count);
}
catch (LobbyServiceException e)
{
Debug.LogError($"Failed to update lobby slots: {e.Message}");
}
}
您可以使用 OnApplicationQuit 方法在应用程序关闭之前管理清理工作。这对于处理玩家离开游戏时的断开连接特别有帮助,无论他们是正常这样做还是使用 Alt+F4 等快捷键。