c# – Unity Force quit handle

I am using a lobby in the Unity engine, and when the user presses Alt+F4 to force quit, I would like to write a script that will force the user to leave the lobby and then quit if they are in the lobby.

I tried using the OnApplicationquit() function, but a problem occurred.

My Code:

    public async void LeaveLobby()
    {
        try
        {
            Debug.Log("b");
            if (joinedLobby.Players.Count > 1) {
                if (IsLobbyHost())
                {
                    MigrateLobbyHost();
                }
            }
            Debug.Log("abc");
            await LobbyService.Instance.RemovePlayerAsync(joinedLobby.Id, AuthenticationService.Instance.PlayerId);
            Debug.Log("c");
            joinedLobby = null;
            OnLeftLobby?.Invoke(this, EventArgs.Empty);
            Show();
            Debug.Log("a");
        }



    private void OnApplicationQuit()
    {
        Debug.Log("Quit!");
        LeaveLobby();
        Debug.Log("Quited!");
    }

When I run this code, the following message will appear when forced to quit (runs normally in play mode, but a problem occurs in the program through build)

enter image description here

How do I successfully exit the lobby when forced to close?

Read more here: Source link