首页 > 解决方案 > 如果 Photon Network 突然断开或用户将网络从 wifi 切换到 Unity3d 中的数据,如何快速重新连接?

问题描述

我开发了一个像 8 球台球这样的游戏。我正在使用光子网络进行多人游戏功能。游戏运行良好,但在某些情况下除外:

  1. 光子网络突然断开。
  2. 如果用户尝试将网络(例如 WiFi)切换到移动数据,则无法再连接 Photon 网络(由于 IP 地址更改)。

为了解决这个问题,我尝试了这个:

  public override void OnDisconnectedFromPhoton() {
        Debug.Log("Disconnected from photon");
        PhotonNetwork.ReconnectAndRejoin();
    }

但它不能正常工作。

对于配对,我是这样写的:

public void JoinRoomAndStartGame()
    {
        ExitGames.Client.Photon.Hashtable expectedCustomRoomProperties = new ExitGames.Client.Photon.Hashtable() { { "tbl", GameManager.Instance.tableNumber }, { "isAvailable", true} };
        PhotonNetwork.JoinRandomRoom(expectedCustomRoomProperties, 0);

    }


    public void OnPhotonRandomJoinFailed()
    {
        RoomOptions roomOptions = new RoomOptions();
        roomOptions.PlayerTtl = 15000;
        roomOptions.CustomRoomPropertiesForLobby = new String[] { "tbl", "isAvailable" };
        roomOptions.CustomRoomProperties = new ExitGames.Client.Photon.Hashtable() { { "tbl", GameManager.Instance.tableNumber }, { "isAvailable", true} };
        roomOptions.MaxPlayers = 2;
        roomOptions.IsVisible = true;
        PhotonNetwork.CreateRoom(null, roomOptions, TypedLobby.Default);
    }

我是光子新手。在这些情况下如何正确重新连接?

标签: c#unity3dnetworkingphoton

解决方案


public override void OnDisconnected(DisconnectCause cause)
{
    StartCoroutine(MainReconnect());  
}
private IEnumerator MainReconnect()
{
    while (PhotonNetwork.NetworkingClient.LoadBalancingPeer.PeerState != ExitGames.Client.Photon.PeerStateValue.Disconnected)
    {
        Debug.Log("Waiting for client to be fully disconnected..", this);

        yield return new WaitForSeconds(0.2f);
    }

    Debug.Log("Client is disconnected!", this);

    if (!PhotonNetwork.ReconnectAndRejoin())
    {
        if (PhotonNetwork.Reconnect())
        {
            Debug.Log("Successful reconnected!", this);
        }
    }
    else
    {
        Debug.Log("Successful reconnected and joined!", this);
    }
}

推荐阅读