Search Unity

Resolved How to do host migration?

Discussion in 'Lobby' started by geronimo_desenvolvimentos, Mar 15, 2022.

  1. geronimo_desenvolvimentos

    geronimo_desenvolvimentos

    Joined:
    May 24, 2013
    Posts:
    17
    The docs in https://docs.unity.com/lobby/host-migration.html are very unhelpful. I tried to do host migration to the best of my understanding but the host does not migrate from the host that is leaving to the remaining client.

    How does host migration actually works? I want one of the remaining players to be the new host and go on playing with the other players.



    Code (CSharp):
    1. private IEnumerator Quit()
    2.     {
    3.         Debug.Log("Beginning");
    4.         var getLobbyTask = Lobbies.Instance.GetLobbyAsync(State.Value.Lobby.Id);
    5.         yield return new WaitWhile(() => getLobbyTask.IsCompleted == false);
    6.         var updatedLobby = getLobbyTask.Result;
    7.         updatedLobby.Players.ForEach(player =>
    8.         {
    9.             Debug.Log($"player {player.Id}, allocationId {player.AllocationId}");
    10.         });
    11.         if (NetworkManager.Singleton.IsHost)
    12.         {
    13.             Debug.Log("I am the host, have to migrate host to someone else");
    14.             Player oldHost = updatedLobby.Players.Where(p => p.AllocationId != null && p.AllocationId != "").First();
    15.             Player newHost = updatedLobby.Players.Where(p => p.AllocationId == null || p.AllocationId == "").First();
    16.             UpdateLobbyOptions updateOptions = new UpdateLobbyOptions()
    17.             {
    18.                 HostId=newHost.Id
    19.             };
    20.             var t = Lobbies.Instance.UpdateLobbyAsync(updatedLobby.Id, updateOptions);
    21.             yield return new WaitWhile(() => t.IsCompleted == false);
    22.             Debug.Log("Supposedly the other player is the host now.");
    23.         }
    24.         Debug.Log("Leaving the lobby");
    25.         var t1 = Lobbies.Instance.RemovePlayerAsync(updatedLobby.Id, AuthenticationService.Instance.PlayerId);
    26.         yield return new WaitWhile(() => t1.IsCompleted == false);
    27.         Debug.Log("shutting down network");
    28.         NetworkManager.Singleton.DisconnectClient(NetworkManager.Singleton.LocalClientId);
    29.         NetworkManager.Singleton.Shutdown(true);
    30.         yield return new WaitWhile(() => NetworkManager.Singleton.ShutdownInProgress);
    31.         var isDone = false;
    32.         Debug.Log("back to home scen");
    33.         SceneManager.LoadSceneAsync("Scenes/Home").completed += (c) =>
    34.         {
    35.             isDone = c.isDone;
    36.         };
    37.         yield return new WaitWhile(() => isDone == false);
    38.         Destroy(gameObject);
     
    JayHuangYC likes this.
  2. UnityKip

    UnityKip

    Unity Technologies

    Joined:
    Nov 15, 2021
    Posts:
    36
    Hi @don_geronimo_hue

    Thank you for participating in the Lobby open beta.

    I believe your code currently circumvents the host migration process here:
    Code (CSharp):
    1. Debug.Log("I am the host, have to migrate host to someone else");
    2.             Player oldHost = updatedLobby.Players.Where(p => p.AllocationId != null && p.AllocationId != "").First();
    3.             Player newHost = updatedLobby.Players.Where(p => p.AllocationId == null || p.AllocationId == "").First();
    4.             UpdateLobbyOptions updateOptions = new UpdateLobbyOptions()
    5.             {
    6.                 HostId=newHost.Id
    7.             };
    Specifically, newHost is being set to the first Player in the Lobby that does not have an AllocationId on line 3. However, this would indicate that the Player is not currently connected to the Lobby. If you're trying to follow the first option of the linked Host Migration doc then I believe you'll want to set newHost to a value that matches up with current client. Perhaps something like this would work for you:

    Code (CSharp):
    1. Debug.Log("I am the host, have to migrate host to someone else");
    2.             Player oldHost = updatedLobby.HostId;
    3.             Player newHost = updatedLobby.Players.Where(p => p.Id != oldHost.Id).First();
    4.             UpdateLobbyOptions updateOptions = new UpdateLobbyOptions()
    5.             {
    6.                 HostId=newHost.Id
    7.             };
    For the other options, you should see a host migration by calling something similar to the following on the host or by disconnecting from an associated Relay:
    Code (CSharp):
    1. RemovePlayerAsync(updatedLobby.Id, updatedLobby.HostId);
    Note that the automatic migrations are not instantaneous but should happen prior to the Lobby being deleted due to inactivity. In addition, please note the Relay migration caveat:

    Let me know if you continue to see issues with the host migration process with the changes above.

    Finally, I'd like to submit a feature request to the Lobby team to automatically migrate hosts when a Lobby's HostId is set to an invalid value. Please let us know your opinion on this suggestion and if it would better meet your expectations for how the SDK should work.

    Regards,
    -Kip
     
  3. geronimo_desenvolvimentos

    geronimo_desenvolvimentos

    Joined:
    May 24, 2013
    Posts:
    17
    Thank you for your time. I created a minimum example, to be used as component of a Netcode for Game Objects' NetworkManager,of how I am using relay+lobby. In this example host migration does not happen.

    There is also a strange, in my opinion, behavior. Alice sets the allocationId (line 109) when the host creates the lobby and relay (CreateMyRelayAndMyLobby). But when Bob quick joins Alice's lobby (TryToJoinExistingLobbyOrCreateNewIfNoneFound) Alice's allocationId is nowhere to be found (it didn't appear on the logs) and the host migration fails when the button that calls OnMigrateClick is clicked.

    From what I understood the allocationId is the link between the Relay and Lobby and if it isn't there the lobby won't play along with the relay. Is this correct?

    What am I doing wrong?

    I don't know it it matters but I am doing the tests using two editor instances on the same machine, cloned using ParrelSync.
    Relay is @ 1.0.1-pre.6,
    Unity Transport for Netcode for Game Objects @ 1.0.0-pre.6
    Netcode For Game Objects @ 1.0.0-pre.6
    Lobby @ 1.0.0-pre.6
    Authentication 1.0.0-pre.37

    Operating System is Win10, Unity 2020.3.29f1.1603 Personal

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.Threading.Tasks;
    4. using Unity.Services.Authentication;
    5. using Unity.Services.Core;
    6. using Unity.Services.Lobbies;
    7. using Unity.Services.Lobbies.Models;
    8. using UnityEngine;
    9. using System.Linq;
    10. using Unity.Services.Relay;
    11. using Unity.Services.Relay.Models;
    12. using Unity.Netcode;
    13. using System;
    14.  
    15. public class HostMigrationTest : MonoBehaviour
    16. {
    17.     /// <summary>
    18.     /// It's value comes from either TryToQuickJoin or CreateMyRelayAndMyLobby
    19.     /// </summary>
    20.     private Lobby lobby;
    21.     /// <summary>
    22.     /// It's value comes from either CreateRelayAllocation
    23.     /// </summary>
    24.     private Allocation allocation;
    25.     /// <summary>
    26.     /// Comes from TryToJoinExistingLobbyOrCreateNewIfNoneFound
    27.     /// </summary>
    28.     private JoinAllocation joinAllocation;
    29.     private string joinCode;
    30.     public async void Start()
    31.     {
    32.         Debug.Log("??");
    33.         await InitializeServicesAndSignInAsync();
    34.         await TryToJoinExistingLobbyOrCreateNewIfNoneFound();
    35.     }
    36.     /// <summary>
    37.     /// Is there a lobby that I can join using quick join? If there is such a lobby
    38.     /// then join it, get it's allocation and join the relay. If not create the relay
    39.     /// and create the lobby.
    40.     /// </summary>
    41.     /// <returns></returns>
    42.     private async Task TryToJoinExistingLobbyOrCreateNewIfNoneFound()
    43.     {
    44.         try
    45.         {
    46.             await TryToQuickJoin();
    47.             Debug.Log("If I arrived here I found an open lobby.");
    48.             ///Maybe there is a issue here: when Alice creates a Lobby it sets an allocationId on herself.
    49.             ///But when Bob gets the lobby created by Alice via quick join Alice's allocationId is gone.
    50.             Debug.Log($"id:{lobby.Id}, hostId:{lobby.HostId}, numberOfPlayers:{lobby.Players.Count}, " +
    51.                 $"allocationId:{lobby.Players.Where(p=>p.Id==lobby.HostId).First().AllocationId}");
    52.             var connectionInfo = lobby.Players.Where(p => p.Id == lobby.HostId).First().ConnectionInfo;
    53.             joinAllocation = await Relay.Instance.JoinAllocationAsync(connectionInfo);
    54.         }
    55.         catch (LobbyServiceException e)
    56.         {
    57.             if (e.Reason == LobbyExceptionReason.NoOpenLobbies)
    58.             {
    59.                 Debug.Log("no lobby found, creating my own lobby");
    60.                 await CreateMyRelayAndMyLobby();
    61.             }
    62.             else
    63.             {
    64.                 throw e;
    65.             }
    66.         }
    67.     }
    68.  
    69.     private async Task InitializeServicesAndSignInAsync()
    70.     {
    71.         try
    72.         {
    73.             await UnityServices.InitializeAsync();
    74.             await AuthenticationService.Instance.SignInAnonymouslyAsync();
    75.             Debug.Log("init done");
    76.         }
    77.         catch(Exception ex)
    78.         {
    79.             Debug.LogError(ex);
    80.         }
    81.     }
    82.     /// <summary>
    83.     /// Join an existing lobby. ***IS THIS CORRECT?***
    84.     /// </summary>
    85.     /// <returns></returns>
    86.     private async Task TryToQuickJoin()
    87.     {
    88.         Debug.Log("Looking for existing lobby");
    89.         QuickJoinLobbyOptions options = new QuickJoinLobbyOptions();
    90.         options.Filter = new List<QueryFilter>()
    91.             {
    92.                 new QueryFilter(
    93.                 field: QueryFilter.FieldOptions.MaxPlayers,
    94.                 op: QueryFilter.OpOptions.GE,
    95.                 value: "2"
    96.                 )
    97.             };
    98.         lobby = await Lobbies.Instance.QuickJoinLobbyAsync();
    99.     }
    100.     /// <summary>
    101.     /// Create the allocation and then the lobby using the allocation data.
    102.     /// </summary>
    103.     /// <returns></returns>
    104.     private async Task CreateMyRelayAndMyLobby()
    105.     {
    106.         await CreateRelayAllocation();
    107.         CreateLobbyOptions o = new CreateLobbyOptions();
    108.         o.IsPrivate = false;
    109.         o.Player = new Player(
    110.             allocationId: allocation.AllocationId.ToString(),//****Alice's allocationId: is this correct ?****
    111.             connectionInfo: joinCode,//****is this correct ?****
    112.             id: AuthenticationService.Instance.PlayerId
    113.             );
    114.         lobby = await Lobbies.Instance.CreateLobbyAsync("foobar", 2, o);
    115.         Debug.Log($"Created my lobby:{lobby.Id}, host:{lobby.HostId}, number of" +
    116.             $"players:{lobby.Players.Count}");
    117.     }
    118.     /// <summary>
    119.     /// Creates the allocation, the values that matter go to the allocation and joinCode
    120.     /// fields.
    121.     /// </summary>
    122.     /// <returns></returns>
    123.     private async Task CreateRelayAllocation()
    124.     {
    125.         allocation = await Relay.Instance.CreateAllocationAsync(2);
    126.         joinCode = await Relay.Instance.GetJoinCodeAsync(allocation.AllocationId);
    127.         Debug.Log($"Created allocation:{allocation.AllocationId}");
    128.     }
    129.     private bool createdHost = false;
    130.     private bool createdClient = false;
    131.     public void Update()
    132.     {
    133.         var nm = NetworkManager.Singleton;
    134.         if (allocation!=null && createdHost == false)
    135.         {
    136.             createdHost = true;
    137.             nm.StartHost();
    138.         }
    139.         if(joinAllocation!=null && createdClient == false)
    140.         {
    141.             createdClient = true;
    142.             nm.StartClient();
    143.         }
    144.     }
    145.     public void OnMigrateClick()
    146.     {
    147.         Debug.Log("clicou");
    148.         doMigrate();
    149.     }
    150.     private async void doMigrate()
    151.     {
    152.         var updatedLobby = await Lobbies.Instance.GetLobbyAsync(lobby.Id);
    153.         var nm = NetworkManager.Singleton;
    154.         if (nm.IsHost)
    155.         {
    156.             Debug.Log("I am the host, have to migrate host to someone else");
    157.             Lobby shouldHaveDifferentHost = await Lobbies.Instance.UpdateLobbyAsync(updatedLobby.Id, new UpdateLobbyOptions()
    158.             {
    159.                 HostId = updatedLobby.Players.Where(p => p.Id != updatedLobby.HostId).First().Id
    160.             });
    161.             Debug.Log($"Has the host id changed? {shouldHaveDifferentHost.HostId != updatedLobby.HostId}");
    162.             await Lobbies.Instance.RemovePlayerAsync(updatedLobby.Id, updatedLobby.HostId);
    163.             await Task.Delay(5000);//Waiting because host migration is not instantaneous
    164.             Debug.Log("Waited for migration, time do disconnect from the game");
    165.             nm.DisconnectClient(nm.LocalClientId);
    166.             nm.Shutdown(true);
    167.             Debug.Log("I am dead. Did the host migrate?");
    168.         }
    169.     }
    170. }
    171.  
     
    Last edited: Mar 15, 2022
  4. UnityKip

    UnityKip

    Unity Technologies

    Joined:
    Nov 15, 2021
    Posts:
    36
    Hi @don_geronimo_hue

    It took awhile to dig into this and respond. There are a few things happening that are likely confounding your migration tests.

    The key takeaway is that Host Migration is not currently available when using NGO (Netcode for Game Objects). If Host Migration is critical to your game, I recommend using UTP (Unity Transport Protocol) [Relay Integration] as your transport instead of NGO.

    An immense amount of details are being omitted here because the nuance could be completely irrelevant by the end of the beta and might be misleading. However, if you'd like additional information, please open a support ticket through your Unity Dashboard under Help & Support -> File a Ticket -> Multiplayer -> Lobby and I can fill in the omissions.

    As far as your code goes (ignoring NGO), there were a few things that you could adjust that will ensure Host Migration is working between Relay and Lobby:
    1. When your client joins the Lobby, they should update their own Lobby.Player.AllocationId to match the current host and ensure Lobby automatically updates when Relay detects a player disconnect.
    2. During the migration, the new host will need to create a new Relay Allocation and update the values in the Lobby so that other clients can connect and join.
      • Note: If you manually migrate a Lobby host (as in your code), you should still create a new Relay Allocation and update the information.
    Outside of the above, your minimal example was properly migrating in my own project so I suspect you were just running into issues with NGO.

    I do know that you've requested a better demonstration for these behaviors in another thread, but please let me know if you had any other requests or suggestions you have for the development team and I'll forward them along.

    -Kip
     
    OrangeSensei likes this.
  5. AsifNaeem

    AsifNaeem

    Joined:
    Apr 12, 2016
    Posts:
    29
    There should be an ownership/host transfer option that allows for a seamless transition without disrupting the ongoing game session. In my current scenario, where five players are connected in a puzzle game, if the host decides to leave, the current system removes all remaining players from the session. It would be beneficial to implement a solution that ensures the departure of a host does not disturb the continuity of the game for the entire party. Is there a way to handle this, so that if a player leaves, the entire party does not get removed from the session?
     
  6. amirhosseinasa

    amirhosseinasa

    Joined:
    Nov 30, 2022
    Posts:
    4
    Hi,
    Did you find any solution?
     
  7. amirhosseinasa

    amirhosseinasa

    Joined:
    Nov 30, 2022
    Posts:
    4

    Hi,
    Did you find any solution?
     
  8. AsifNaeem

    AsifNaeem

    Joined:
    Apr 12, 2016
    Posts:
    29
    Unity does not provide any way to migrate the host.
     
  9. qngnht

    qngnht

    Joined:
    Jan 24, 2022
    Posts:
    24
    After Host quit:
    Step 1 : make 2nd Client create a new Lobby and become new Host.
    Step 2: All other Clients will join in new Lobby as Client.
    Step 3: Old Host reconnect to new Lobby as Client.
    Host mirate is successful !
    I did it successfully and showed video on youtube.
     
    isaiasmegacat likes this.
  10. isaiasmegacat

    isaiasmegacat

    Joined:
    Feb 29, 2024
    Posts:
    5
    Where's the video, please?
     
  11. qngnht

    qngnht

    Joined:
    Jan 24, 2022
    Posts:
    24
    Search for Unity No Code : Unity How to make game online in Visual Scripting
    It's not easy to show how I made it ... You have to code it by yourself ^ ^