Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Resolved 'OnClientDisconnectedCallback' isn't excuted.

Discussion in 'Netcode for GameObjects' started by Sushi8819, Oct 25, 2023.

  1. Sushi8819

    Sushi8819

    Joined:
    Oct 20, 2023
    Posts:
    17
    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.

    Code (CSharp):
    1.    
    2. public override void OnNetworkSpawn()
    3. {
    4.     if (IsServer)
    5.     {
    6.             NetworkManager.Singleton.OnClientConnectedCallback += HandleClientConnected;
    7.             NetworkManager.Singleton.OnClientDisconnectCallback += HandleClientDisconnected;
    8.     }
    9. }
    10. public override void OnNetworkDespawn()
    11. {
    12.     if (IsServer)
    13.    {
    14.             NetworkManager.Singleton.OnClientConnectedCallback -= HandleClientConnected;
    15.             NetworkManager.Singleton.OnClientDisconnectCallback -= HandleClientDisconnected;
    16.    }
    17. }
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    7,263
    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.
     
    Sushi8819 likes this.
  3. Sushi8819

    Sushi8819

    Joined:
    Oct 20, 2023
    Posts:
    17
    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.

    Code (CSharp):
    1.    
    2. private void OnDisable()
    3. {
    4.     if (NetworkManager.Singleton != null)
    5.     {
    6.         NetworkManager.Singleton.OnClientConnectedCallback -= ClientConnectListner;
    7.         NetworkManager.Singleton.OnClientDisconnectCallback -= ClientDisconnectListener;
    8.     }
    9. }
     
    CodeSmile likes this.