Unity 向け Multiplay Hosting SDK
Integrate Multiplay Hosting functionality into your Unity game server.
読み終わるまでの所要時間 7 分最終更新 4日前
Unity 向け Multiplay Hosting SDK は、ゲームで Multiplay Hosting のスケーリングとゲームサーバーサービスを使用するために必要なすべての機能を備えています。
Unity.Services.Multiplay要件と制限事項
Unity 向け Multiplay Hosting SDK は、Unity エディターバージョン 2020.3 以降で動作します。SDK を初期化する
Instance メソッドを使用して、IMultiplayServiceasync void Example_InitSDK(){ try { await UnityServices.InitializeAsync(); } catch (Exception e) { Debug.Log(e); }}
ゲームサーバーを設定する
ServerConfigServerConfigServerConfigServerConfigServerConfigパラメーター | 型 | 説明 |
|---|---|---|
| long | サーバー ID。 |
| string | 割り当て ID。 |
| ushort | サーバークエリプロトコル のポート番号。 |
| ushort | ゲームセッションの接続ポート。これは、ゲームクライアントがゲームセッションに接続するために使用できるポート番号です。 |
| string | ゲームサーバーがログファイルを保存するディレクトリ。 |
ServerConfigusing System.Collections;using System.Collections.Generic;using Unity.Services.Multiplay;using UnityEngine;public class Example_ServerConfiguration{ /// <summary> /// A simple example of accessing each of the server config's fields and printing them to the debug console. /// </summary> public static void LogServerConfig() { var serverConfig = MultiplayService.Instance.ServerConfig; Debug.Log($"Server ID[{serverConfig.ServerId}]"); Debug.Log($"AllocationID[{serverConfig.AllocationId}]"); Debug.Log($"Port[{serverConfig.Port}]"); Debug.Log($"QueryPort[{serverConfig.QueryPort}"); Debug.Log($"LogDirectory[{serverConfig.ServerLogDirectory}]"); }}
ゲームサーバーを準備完了にする
ReadyServerForPlayersAsyncusing System.Threading.Tasks;using Unity.Services.Multiplay;/// <summary>/// Ready the server. This is to indicate that the server is ready to accept players./// Readiness is the server's way of saying it's ready for players to join the server./// You must wait until you have been Allocated before you can call ReadyServerForPlayersAsync./// </summary>private async void Example_ReadyingServer(){ // After the server is back to a blank slate and ready to accept new players await MultiplayService.Instance.ReadyServerForPlayersAsync();}
ゲームサーバーを準備未完了にする
UnreadyServerAsyncusing System.Threading.Tasks;using Unity.Services.Multiplay;/// <summary>/// Unready the server. This is to indicate that the server is in some condition which means it can't accept players./// For example, after a game has ended and you need to reset the server to prepare for a new match./// </summary>private async void Example_UnreadyingServer(){ // The match has ended and players are disconnected from the server await MultiplayService.Instance.UnreadyServerAsync();}
サーバークエリハンドラーを開始する
StartServerQueryHandlerAsyncパラメーター | 型 | 説明 |
|---|---|---|
| ushort | サーバー上のプレイヤーの最大数。 |
| string | サーバーの名前。 |
| string | サーバーが実行しているゲームのタイプを表す名前または識別子。 |
| string | ゲームのバージョン。 |
| string | サーバーがゲームのために実行しているマップまたはワールド。 |
| ushort | ゲームクライアントが接続するために使用できるゲームサーバーのポート番号。 |
StartServerQueryHandlerAsyncparametersIServerCheckManagerUpdateServerCheck()UpdateServerCheck()
以下の例は、サーバークエリハンドラーを開始する方法を示しています。
using System.Collections;using System.Collections.Generic;using UnityEngine;using Unity.Services.Multiplay;/// <summary>/// An example of how to use SQP from the server using the Multiplay SDK./// The ServerQueryHandler reports the given information to the Multiplay Service./// </summary>public class Example_ServerQueryHandler : MonoBehaviour{ private const ushort k_DefaultMaxPlayers = 10; private const string k_DefaultServerName = "MyServerExample"; private const string k_DefaultGameType = "MyGameType"; private const string k_DefaultBuildId = "MyBuildId"; private const string k_DefaultMap = "MyMap"; public ushort currentPlayers; private IServerQueryHandler m_ServerQueryHandler; private async void Start() { m_ServerQueryHandler = await MultiplayService.Instance.StartServerQueryHandlerAsync(k_DefaultMaxPlayers, k_DefaultServerName, k_DefaultGameType, k_DefaultBuildId, k_DefaultMap); } private void Update() { m_ServerQueryHandler.UpdateServerCheck(); } public void ChangeQueryResponseValues(ushort maxPlayers, string serverName, string gameType, string buildId) { m_ServerQueryHandler.MaxPlayers = maxPlayers; m_ServerQueryHandler.ServerName = serverName; m_ServerQueryHandler.GameType = gameType; m_ServerQueryHandler.BuildId = buildId; } public void PlayerCountChanged(ushort newPlayerCount) { m_ServerQueryHandler.CurrentPlayers = newPlayerCount; }}
サーバーイベントにサブスクライブする
SubscribeToServerEventsAsyncOnAllocateOnDeallocateOnErrorusing System;using System.Collections;using System.Collections.Generic;using Unity.Services.Multiplay;using UnityEngine;/// <summary>/// An example of how to access and react to multiplay server events./// </summary>public class Example_ServerEvents : MonoBehaviour{ private MultiplayEventCallbacks m_MultiplayEventCallbacks; private IServerEvents m_ServerEvents; /// <summary> /// This should be done early in the server's lifecycle, as you'll want to receive events as soon as possible. /// </summary> private async void Start() { // We must first prepare our callbacks like so: m_MultiplayEventCallbacks = new MultiplayEventCallbacks(); m_MultiplayEventCallbacks.Allocate += OnAllocate; m_MultiplayEventCallbacks.Deallocate += OnDeallocate; m_MultiplayEventCallbacks.Error += OnError; m_MultiplayEventCallbacks.SubscriptionStateChanged += OnSubscriptionStateChanged; // We must then subscribe. m_ServerEvents = await MultiplayService.Instance.SubscribeToServerEventsAsync(m_MultiplayEventCallbacks); }// Handle Multiplay events.}
Multiplay Hosting イベントを処理する
MultiplayEventCallbacksOnAllocateOnDeallocateOnErrorusing System;using System.Collections;using System.Collections.Generic;using Unity.Services.Multiplay;using UnityEngine;/// <summary>/// An example of how to access and react to multiplay server events./// </summary>public class Example_ServerEvents : MonoBehaviour{ private MultiplayEventCallbacks m_MultiplayEventCallbacks; private IServerEvents m_ServerEvents; /// <summary> /// This should be done early in the server's lifecycle, as you'll want to receive events as soon as possible. /// </summary> private async void Start() { // We must first prepare our callbacks like so: m_MultiplayEventCallbacks = new MultiplayEventCallbacks(); m_MultiplayEventCallbacks.Allocate += OnAllocate; m_MultiplayEventCallbacks.Deallocate += OnDeallocate; m_MultiplayEventCallbacks.Error += OnError; m_MultiplayEventCallbacks.SubscriptionStateChanged += OnSubscriptionStateChanged; // We must then subscribe. m_ServerEvents = await MultiplayService.Instance.SubscribeToServerEventsAsync(m_MultiplayEventCallbacks); } /// <summary> /// Handler for receiving the allocation multiplay server event. /// </summary> /// <param name="allocation">The allocation received from the event.</param> private void OnAllocate(MultiplayAllocation allocation) { // Here is where you handle the allocation. // This is highly dependent on your game, however this would typically be some sort of setup process. // Whereby, you spawn NPCs, setup the map, log to a file, or otherwise prepare for players. // After you the allocation has been handled, you can then call ReadyServerForPlayersAsync()! } /// <summary> /// Handler for receiving the deallocation multiplay server event. /// </summary> /// <param name="deallocation">The deallocation received from the event.</param> private void OnDeallocate(MultiplayDeallocation deallocation) { // Here is where you handle the deallocation. // This is highly dependent on your game, however this would typically be some sort of teardown process. // You might want to deactivate unnecessary NPCs, log to a file, or perform any other cleanup actions. } /// <summary> /// Handler for receiving the error multiplay server event. /// </summary> /// <param name="error">The error received from the event.</param> private void OnError(MultiplayError error) { // Here is where you handle the error. // This is highly dependent on your game. You can inspect the error by accessing the error.Reason and error.Detail fields. // You can change on the error.Reason field, log the error, or otherwise handle it as you need to. } /// <summary> /// /// </summary> /// <param name="state"></param> private void OnSubscriptionStateChanged(MultiplayServerSubscriptionState state) { switch (state) { case MultiplayServerSubscriptionState.Unsubscribed: /* The Server Events subscription has been unsubscribed from. */ break; case MultiplayServerSubscriptionState.Synced: /* The Server Events subscription is up to date and active. */ break; case MultiplayServerSubscriptionState.Unsynced: /* The Server Events subscription has fallen out of sync, the subscription tries to automatically recover. */ break; case MultiplayServerSubscriptionState.Error: /* The Server Events subscription has fallen into an errored state and won't recover automatically. */ break; case MultiplayServerSubscriptionState.Subscribing: /* The Server Events subscription is trying to sync. */ break; } }}
割り当て
public event Action<MultiplayAllocation> Allocate;
AllocateMultiplayAllocation割り当て解除
public event Action<MultiplayDeallocation> Deallocate;
DeallocateMultiplayDeallocationError
public event Action<MultiplayError> Error;
ErrorMultiplayErrorSubscriptionStateChange
public event Action<MultiplayServerSubscriptionState> SubscriptionStateChanged;
SubscriptionStateChangedMultiplayServerSubscriptionStateUnity エディターを使用したリソースのデプロイ
Multiplay オーサリングモジュール (Multiplay パッケージとともにインストールされる) を使用すると、任意で、リソースのオーサリングと変更を Unity エディター内で直接的に行うことができます。その後、Deployment パッケージ を使用して、Unity エディターからダッシュボードにリソースをアップロードできます。 Unity エディターに存在する Multiplay 設定を使用すると、ユーザーは (クラウド内のバージョンの代わりに) ソース管理を信頼できる唯一の情報源として扱うことができ、ロールバック、二等分、その他の一般的な操作のアクションが簡略化されます。Multiplay の設定
Unity エディターで Multiplay を使用するには、以下を行ってください。必要なパッケージをインストールする
エディター内で Multiplay 設定を作成するには、以下のパッケージをインストールします。- Deployment
- Multiplay:
- Unity 6 以降: マルチプレイヤー
- Unity 2022 LTS 以前: Multiplay
これらのパッケージをインストールして、使用可能なパッケージのリストに追加するには、以下を行います。
- Unity エディターで、Window (ウィンドウ) > Package Manager (パッケージマネージャー) を選択します。
- + > Install package by name (名前を指定してパッケージをインストール) を選択します。
- を入力します。
com.unity.services.deployment - Install (インストール) を選択します。
- これらのステップを Multiplay について繰り返します。
- Unity 6 以降:
com.unity.services.multiplayer - Unity 2022 LTS 以前:
com.unity.services.multiplay
- Unity 6 以降:
プロジェクトのリンク
Unity Gaming Services プロジェクト を Unity エディターにリンクします。UGS プロジェクト ID は Unity Dashboard にあります。- Unity エディターで、Edit (編集) > Project Settings (プロジェクト設定) > Services (サービス) の順に選択します。
- プロジェクトをリンクします。
- プロジェクトに Unity プロジェクト ID がない場合:
- Create a Unity Project ID (Unity プロジェクト ID の作成) > Organizations (組織) の順に選択し、ドロップダウンメニューから組織を選択します。
- Create project ID (プロジェクト ID を作成) を選択します。
- 既存の Unity プロジェクト ID がある場合:
- Use an existing Unity project ID (既存の Unity プロジェクト ID を使用) を選択します。
- ドロップダウンメニューから組織とプロジェクトを選択します。
- Link project ID (プロジェクト ID をリンク) を選択します。
UnityEditor.CloudProjectSettings.projectIdUnity エディター内でのオーサリング
Multiplay オーサリングモジュールを使用すると、直接 Unity エディター内で、Multiplay 設定の作成、編集、デプロイを行うことができます。設定の作成
以下のステップに従い、Multiplay オーサリングモジュールを使用して Multiplay 設定を作成します。- Unity エディターで、Project (プロジェクト) ウィンドウを右クリックし、Create (作成) > Services (サービス) > Multiplay Config (Multiplay 設定) を選択します。
- リソースファイルの名前を指定します。
- Enter を押します。
設定の編集
現在、既存の設定を編集する方法は 1 つです。- Project (プロジェクト) タブで、既存のリソースをダブルクリックし、任意のテキストエディターを選択して設定を編集します。
リソースファイルのコンテンツ
Deployment (デプロイ) ウィンドウは、リソースを検出し、ファイル拡張子に応じてタイプを割り当てます。 この設定では、内容を記述するためのyaml.gshnew_multiplay_config.gshこの設定ではファイル内で 3 つのコンポーネントが記述されています。version: 1.0builds: my build: # replace with the name for your build executableName: Build.x86_64 # the name of your build executable buildPath: Builds/Multiplay # the location of the build filesbuildConfigurations: my build configuration: # replace with the name for your build configuration build: my build # replace with the name for your build queryType: sqp # sqp or a2s, delete if you do not have logs to query binaryPath: Build.x86_64 # the name of your build executable commandLine: -port $$port$$ -queryport $$query_port$$ -log $$log_dir$$/Engine.log # launch parameters for your server variables: {} cores: 1 # number of cores per server speedMhz: 750 # launch parameters for your server memoryMiB: 800 # launch parameters for your serverfleets: my fleet: # replace with the name for your fleet buildConfigurations: - my build configuration # replace with the names of your build configuration regions: North America: # North America, Europe, Asia, South America, Australia minAvailable: 0 # minimum number of servers running in the region maxServers: 1 # maximum number of servers running in the region