Hi everyone,
I’m working on a multiplayer game using Unity Netcode for GameObjects, and I’ve encountered an issue with detecting the host’s disconnection.
I have a HostDisconnectionManager
script attached to an empty GameObject in the scene. Its purpose is to listen for disconnections using the NetworkManager.Singleton.OnClientDisconnectCallback()
event.
I also have a HostDisconnectUI
script attached to my player’s prefab, which handles showing a UI element when the host disconnects.
My goal is for the HostDisconnectionManager
to notify the HostDisconnectUI
on all clients to execute the HostDisconnected()
method when the host disconnects.
The Issue: When the host disconnects, the NetworkManager.Singleton.OnClientDisconnectCallback()
event is triggered as expected. However, the clientId
it provides corresponds to the ClientOwnerId
of the remaining clients instead of the ServerClientId
(which should be 0
for the host). This causes the logic to fail, as the script cannot correctly identify the host disconnection.
Here are the scripts:
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
public class HostDisconnectionManager : MonoBehaviour
{
void Start()
{
NetworkManager.Singleton.OnClientDisconnectCallback += NetworkManager_OnClientDisconnectCallback;
}
void Update()
{
}
void NetworkManager_OnClientDisconnectCallback(ulong clientId)
{
Debug.Log("Host Disconnected: " + clientId);
if ( clientId == NetworkManager.ServerClientId)
{
Debug.Log("Host has disconnected!");
HostDisconnectUI[] ui = FindObjectsOfType<HostDisconnectUI>();
foreach (HostDisconnectUI ui2 in ui)
{
ui2.HostDisconnected();
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
public class HostDisconnectUI : MonoBehaviour
{
public GameObject hostHasDisconnectedTemplate;
public UnityEngine.UI.Button goToMainMenuButton;
void Start()
{
Hide();
}
public void HostDisconnected()
{
hostHasDisconnectedTemplate.SetActive(true);
}
void Hide()
{
hostHasDisconnectedTemplate.SetActive(false);
}
}
How can I reliably detect the host’s disconnection and notify all player instances to display the host disconnection UI? Any help or insight would be very helpful!
Thank you for your time!