以下の内容はhttps://redhologerbera.hatenablog.com/entry/2021/01/23/185857より取得しました。


Photonのチュートリアルをやる その⑤ルームへの接続と再接続

本日はPhotonのチュートリアル記事です。

〇Photonとは?

PhotonはUnityでのマルチユーザーアプリの実現のためのSDKとその仕組みを指します。

オリジナルのチュートリアルは下記になります。

doc.photonengine.com

今回はルームにいるユーザーの数に応じて処理を行う仕組みを作成します。

例えば3対3で対戦を行うゲームがある場合、ルームに最低6名がいることが条件で初めて機能します。このような仕組みを学びます。

①[GameManager]コンポーネントをエディタで開きます。

②次のメソッドを加えます。

        #region Private Meshods

        void LoadArena()
        {
            if (!PhotonNetwork.IsMasterClient)
            {
                Debug.LogError("PhotonNetwork : Trying to Load a Level but we are not the master Client" );
            }
            Debug.LogFormat( "PhotonNetwork ; Loading Level :{0}",PhotonNetwork.CurrentRoom.PlayerCount);
            PhotonNetwork.LoadLevel("Room for" + PhotonNetwork.CurrentRoom.PlayerCount);
        }

        #endregion
    }

このメソッドでは入室しているプレイヤーの[PlayerCount(人数)]に応じて適切なルームを読み込みます。

このメソッドを読み込むのはマスタークライアントである必要があります。

最初に自信がマスタークライアントであるかどうかを確認します。

 if (!PhotonNetwork.IsMasterClient)
    {
        Debug.LogError("PhotonNetwork : Trying to Load a level but we are not the master Client");
    }

任意のルームレベルに入るためには[PhotonNetwork.LoadLevel()]を呼び出します。

適切なレベルを読み込む機能を設定したので、プレイヤーの接続や切断と連携させます。

〇プレイヤーの接続を管理

[GameManager]コンポーネントに次のメソッドを加えます。

#region Photon Callbacks


public override void OnPlayerEnteredRoom(Player other)
{
    Debug.LogFormat("OnPlayerEnteredRoom() {0}", other.NickName); // not seen if you're the player connecting


    if (PhotonNetwork.IsMasterClient)
    {
        Debug.LogFormat("OnPlayerEnteredRoom IsMasterClient {0}", PhotonNetwork.IsMasterClient); // called before OnPlayerLeftRoom


        LoadArena();
    }
}


public override void OnPlayerLeftRoom(Player other)
{
    Debug.LogFormat("OnPlayerLeftRoom() {0}", other.NickName); // seen when other disconnects


    if (PhotonNetwork.IsMasterClient)
    {
        Debug.LogFormat("OnPlayerLeftRoom IsMasterClient {0}", PhotonNetwork.IsMasterClient); // called before OnPlayerLeftRoom


        LoadArena();
    }
}


#endregion

これでユーザーがルームに入るたびにユーザーに応じた適切な通知が行われます。次にルームに入室できるようにします。

〇アリーナへの接続

①[Launcger]コンポーネントを開き次のメソッドを加えます。

// #Critical: We only load if we are the first player, else we rely on `PhotonNetwork.AutomaticallySyncScene` to sync our instance scene.
if (PhotonNetwork.CurrentRoom.PlayerCount == 1)
{
    Debug.Log("We load the 'Room for 1' ");


    // #Critical
    // Load the Room Level.
    PhotonNetwork.LoadLevel("Room for 1");
}

これはユーザー数が1の場合[Room for 1]へと接続されます。 

しかしこのままでは[Room for 1]に接続し、再びロビーに戻ると強制的に[Room for 1]へまたつながってしまいます。

この問題を解消するためにはフラグをきちんと用意しておく必要があります。

[Launcher]にBool型のフィールドを用意します。

/// <summary>
/// Keep track of the current process. Since connection is asynchronous and is based on several callbacks from Photon,
/// we need to keep track of this to properly adjust the behavior when we receive call back by Photon.
/// Typically this is used for the OnConnectedToMaster() callback.
/// </summary>
bool isConnecting;

[Connect()]に次のように加えます。

  public void Connect()
        {
            // keep track of the will to join a room, because when we come back from the game we will get a callback that we are connected, so we need to know what to do then
            isConnecting = PhotonNetwork.ConnectUsingSettings();//追加
       
     //we check if we are connected or not, we hoin if we are , else we initialize
            if (PhotonNetwork.IsConnected)
            {
             ...
            }
            else
            {
            isConnecting = PhotonNetwork.ConnectUsingSettings();//変更
            PhotonNetwork.GameVersion = gameVersion; //変更
            }
            
        }

[OnConnectedToMaster()]メソッドを[if(isConnecting)]で囲みます。

        public override void OnConnectedToMaster()
        {
            if (isConnecting)
            {
                Debug.Log("PUN Basics Tutorial/Launcher: OnConnectedToMaster() was called by PUN");
                //#Critical: The first we try to do is to hoin a potential existing room.If there is, good, else, we'll be called back with OnJoinRandomFailed()
                PhotonNetwork.JoinRandomRoom();   
            }
        }

 この状態でもう一度Unityでシーンを実行します。 [Room for 1]に接続し再びルームへ戻った際自動的に[Room for 1]へは接続せず任意のタイミングで接続できるようになりました。




以上の内容はhttps://redhologerbera.hatenablog.com/entry/2021/01/23/185857より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14