Relay と Netcode for GameObjects (NGO) の使用
Integrate Relay with Netcode for GameObjects using the unified Multiplayer Services SDK.
読み終わるまでの所要時間 3 分最終更新 1ヶ月前
Relay は、
GameObjectMonoBehaviorRelay SDK を設定する
Relay と NGO を併用する前に、Unity プロジェクトを Unity 用に設定する必要があります。Relay の使用を開始する を参照してください。Relay サービスを有効にし、Unity エディターを通じて Unity プロジェクト ID をリンクしたら、要件をインポートし、NetworkManager要件をインポートする
Relay サービスを使用する前に、Relay SDK と UTP、およびその他の名前空間をインポートする必要があります。パッケージと SDK のダウンロードセンターから生成したコードスニペットを使用してください。- Unity Dashboard にサインインします。
- パッケージと SDK のダウンロードセンター に移動します。
-
以下のパッケージ選択します。
- Relay
- Netcode for GameObjects
- Generate Code Snippet (コードスニペットを生成) を選択し、その後の指示に従います。
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using UnityEngine;using Unity.Services.Core;using Unity.Services.Authentication;using Unity.Services.Relay;using Unity.Services.Relay.Http;using Unity.Services.Relay.Models;using Unity.Netcode;using Unity.Netcode.Transports.UTP;using Unity.Networking.Transport;using Unity.Networking.Transport.Relay;using NetworkEvent = Unity.Networking.Transport.NetworkEvent;
NetworkManager の設定
Unity Dashboard からパッケージをインストールしたら、Unity エディターにある自分のプロジェクトで、NetworkManager- 新しい ゲームオブジェクト をシーンに追加します。
- NetworkManager MonoBehavior を追加します。
- MonoBehavior Properties (MonoBehavior のプロパティ) で、UnityTransport トランスポートを選択します。UnityTransport を選択すると、コンポーネントリストの一番下に Unity Transport (script) という が表示されます。
MonoBehavior - 新しいコンポーネントの Protocol Type (プロトコルタイプ) を Relay Unity Transport に設定します。
変数とユーティリティ関数を設定する
最大接続数や参加コードなど、いくつかの変数の初期化も行う必要があります。const int m_MaxConnections = 4;public string RelayJoinCode;
プレイヤーの認証を行う
ホストプレイヤーと接続プレイヤーの両方の認証を行う必要があります。プレイヤーの認証を行う最も簡単な方法は、Authentication サービスのSignInAnonymouslyAsync()async void Example_AuthenticatingAPlayer(){ try { await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); var playerID = AuthenticationService.Instance.PlayerId; } catch (Exception e) { Debug.Log(e); }}
ホストプレイヤー
ゲームクライアントがホストプレイヤーとして機能する場合、そのゲームクライアントは、割り当ての作成、参加コードのリクエスト、接続の種類の設定、Relay サーバーをバインドして参加プレイヤーからのリクエストをリッスンするためのNetworkDriver割り当てを作成して参加コードをリクエストする
以下のコードスニペットにはAllocateRelayServerAndGetJoinCodepublic static async Task<RelayServerData> AllocateRelayServerAndGetJoinCode(int maxConnections, string region = null){ Allocation allocation; string createJoinCode; try { allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections, region); } catch (Exception e) { Debug.LogError($"Relay create allocation request failed {e.Message}"); throw; } Debug.Log($"server: {allocation.ConnectionData[0]} {allocation.ConnectionData[1]}"); Debug.Log($"server: {allocation.AllocationId}"); try { createJoinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId); } catch { Debug.LogError("Relay create join code request failed"); throw; } return new RelayServerData(allocation, "dtls");}
トランスポートを設定して NGO を起動する
以下のコードスニペットには、ConfigureTransportAndStartNgoAsHostIEnumerator Example_ConfigureTransportAndStartNgoAsHost(){ var serverRelayUtilityTask = AllocateRelayServerAndGetJoinCode(m_MaxConnections); while (!serverRelayUtilityTask.IsCompleted) { yield return null; } if (serverRelayUtilityTask.IsFaulted) { Debug.LogError("Exception thrown when attempting to start Relay Server. Server not started. Exception: " + serverRelayUtilityTask.Exception.Message); yield break; } var relayServerData = serverRelayUtilityTask.Result; // Display the joinCode to the user. NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData); NetworkManager.Singleton.StartHost(); yield return null;}
参加プレイヤー
ゲームクライアントが参加プレイヤーとして機能する場合、そのゲームクライアントは、割り当てへの参加、接続の種類の設定、Relay サーバーにバインドしてホストプレイヤーに接続リクエストを送信するためのNetworkDriver割り当てに参加する
以下のコードスニペットにはJoinRelayServerFromJoinCodepublic static async Task<RelayServerData> JoinRelayServerFromJoinCode(string joinCode){ JoinAllocation allocation; try { allocation = await RelayService.Instance.JoinAllocationAsync(joinCode); } catch { Debug.LogError("Relay create join code request failed"); throw; } Debug.Log($"client: {allocation.ConnectionData[0]} {allocation.ConnectionData[1]}"); Debug.Log($"host: {allocation.HostConnectionData[0]} {allocation.HostConnectionData[1]}"); Debug.Log($"client: {allocation.AllocationId}"); return new RelayServerData(allocation, "dtls");}
トランスポートを設定して NGO を参加プレイヤーとして起動する
以下のサンプルコードは、トランスポートを設定し、Netcode for GameObjects (NGO) を参加プレイヤーとして起動する方法を示しています。IEnumerator Example_ConfigureTransportAndStartNgoAsConnectingPlayer(){ // Populate RelayJoinCode beforehand through the UI var clientRelayUtilityTask = JoinRelayServerFromJoinCode(RelayJoinCode); while (!clientRelayUtilityTask.IsCompleted) { yield return null; } if (clientRelayUtilityTask.IsFaulted) { Debug.LogError("Exception thrown when attempting to connect to Relay Server. Exception: " + clientRelayUtilityTask.Exception.Message); yield break; } var relayServerData = clientRelayUtilityTask.Result; NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData); NetworkManager.Singleton.StartClient(); yield return null;}