Hi.
I want to perform the HandleClientDisconnected process when a client is disconnected from the server, but with the following code, HandleClientDisconnected is not always executed. HandleClientConnected is executed correctly. Am I doing something wrong with my code? Any advice would be appreciated.
public override void OnNetworkSpawn()
{
if (IsServer)
{
NetworkManager.Singleton.OnClientConnectedCallback += HandleClientConnected;
NetworkManager.Singleton.OnClientDisconnectCallback += HandleClientDisconnected;
}
}
public override void OnNetworkDespawn()
{
if (IsServer)
{
NetworkManager.Singleton.OnClientConnectedCallback -= HandleClientConnected;
NetworkManager.Singleton.OnClientDisconnectCallback -= HandleClientDisconnected;
}
}
You are registering these events in an unusual place. Normally you wouldn‘t do this on spawn and despawn, and I would assume that naturally the despawn event happens before disconnecting, but this is where you unregister the disconnect event handler, therefore you do not get that event.
Instead, register and unregister those in OnEnable and OnDisable, or Start and OnDestroy.
1 Like
Hi, CodeSmile.
Thank you for your continued assistance. As you suggested, I moved it to OnEnable and OnDisable, and it worked well! I realized that the order of the despawn event and disconnect event was actually the opposite of what I wanted to achieve. I really appreciate your help.
private void OnDisable()
{
if (NetworkManager.Singleton != null)
{
NetworkManager.Singleton.OnClientConnectedCallback -= ClientConnectListner;
NetworkManager.Singleton.OnClientDisconnectCallback -= ClientDisconnectListener;
}
}
1 Like