I’m creating a 2 player online game. I’d like to show a ‘your opponent left’ information when one of the players leaves.
I understand I can use OnClientDisconnect to detect that client disconnected from server. But the client doesn’t know if it’s because server crashed, lost connection etc, right?
Same with the server side. I can use OnServerDisconnect, but how can I know that the player disconnected from server, because he closed the client, lost connection etc, rather than server losing connection?
This describes what you need
That way you can detect the reason for a disconnect.
I couldn’t find any way to detect the desconnection reason. In our game, when a client wants to leave a match it first executes a Command, so the server knows that the client wanted to disconnect. If the connection is lost and the Command didn’t run, then the client must have lost connection.
As far as I am aware there isn’t any built-in functionality to do this.
I do this for detecting if the server was closed / the client lost connection. Here’s a small flow of how I do it.
I differentiate between the game over state and the game state. If the game has been set to “game over” either through a win condition or the game duration elapsed then when the client returns to the lobby this is valid. Similarly connecting to the lobby via the menu is valid.
Whenever the ‘offline’ scene is loaded if the previous state wasn’t valid for the scene to be loaded I determine that a disconnection. The client isn’t aware of what kind of disconnection that is ( server closed, crashed, etc) but for my purposes it’s sufficient.
When the host disconnects or loses connection to the clients Unity’s
NetworkLobbyManager it loads the lobby scene. This is the same as
NetworkManager loading its offline scene. They are identical if you look inside the code.
Easiest way to do it is set a static flag when the game is loaded and setting the opposite in the menu and on game end.