Unity 向け Multiplay Hosting SDK
ノート: このページの内容は Multiplay Hosting および Clanforge に関連しています。
Unity 向け Multiplay Hosting SDK は、ゲームで Multiplay Hosting のスケーリングとゲームサーバーサービスを使用するために必要なすべての機能を備えています。Unity.Services.Multiplay
は、Multiplay サービスと対話するためのプライマリ名前空間です。
ノート: 先に進む前に、Multiplay Hosting の使用の準備 に関するドキュメントと インテグレーションの要件 を参照してください。
要件と制限事項
Unity 向け Multiplay Hosting SDK は、Unity エディターバージョン 2020.3 以降で動作します。
警告: Unity エディターバージョン 2022 には、SDK が機能しなくなる既知の問題があります。バージョン 2022 を使用する場合は、必ずバージョン 2022.2.3f1 以降を使用してください。
SDK を初期化する
Instance メソッドを使用して、IMultiplayService
のシングルトンを作成します。このシングルトンを使用して、Multiplay Hosting API と対話できます。
async void Example_InitSDK()
{
try
{
await UnityServices.InitializeAsync();
}
catch (Exception e)
{
Debug.Log(e);
}
}
ゲームサーバーを設定する
ServerConfig
クラスはゲームサーバーの設定を表し、これを使用して現在のゲームセッション用の ServerConfig
インスタンスを作成できます。
現在のゲームセッション用の ServerConfig
インスタンスを作成するには、(ServerConfig
クラス内の) ServerConfig
メソッドを使用します。
パラメーター | 型 | 説明 |
---|---|---|
serverId | long | サーバー ID。 |
allocationId | string | 割り当て ID。 |
queryPort | ushort | サーバークエリプロトコル のポート番号。 |
port | ushort | ゲームセッションの接続ポート。これは、ゲームクライアントがゲームセッションに接続するために使用できるポート番号です。 |
serverLogDirectory | string | ゲームサーバーがログファイルを保存するディレクトリ。 |
以下のコード例は、ServerConfig
メソッドを使用してゲームサーバーに関する情報 (サーバー ID、割り当て ID、ポート番号、クエリポート番号、サーバーログディレクトリなど) をログに記録する方法を示しています。
using 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}]");
}
}
ゲームサーバーを準備完了にする
ReadyServerForPlayersAsync
メソッドを使用して、ゲームサーバーがプレイヤーを受け入れる準備ができたことを Multiplay Hosting に通知します。ゲームサーバーの準備状況 に関するドキュメントを参照してください。
using 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();
}
ゲームサーバーを準備未完了にする
UnreadyServerAsync
メソッドを使用して、ゲームサーバーがプレイヤーを受け入れる準備ができなくなったことを Multiplay Hosting に通知します。ゲームサーバーの準備状況 に関するドキュメントを参照してください。
using 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
メソッドを使用して、指定したパラメーターでゲームサーバーの SQP 実装に接続します。
パラメーター | 型 | 説明 |
---|---|---|
maxPlayers | ushort | サーバー上のプレイヤーの最大数。 |
serverName | string | サーバーの名前。 |
gameType | string | サーバーが実行しているゲームのタイプを表す名前または識別子。 |
buildId | string | ゲームのバージョン。 |
map | string | サーバーがゲームのために実行しているマップまたはワールド。 |
port | ushort | ゲームクライアントが接続するために使用できるゲームサーバーのポート番号。 |
Multiplay Hosting では、StartServerQueryHandlerAsyncparameters
を使用してサーバークエリハンドラーを初期化します。
サーバークエリハンドラーを初期化した後は、この呼び出しによって提供される IServerCheckManager
インスタンスを使用していつでも値を更新できます。変更を有効にするには、UpdateServerCheck()
を呼び出す必要があります。UpdateServerCheck()
は、ゲームサーバーの変数が変更されたときに呼び出します。詳細については、SQP に関するドキュメントを参照してください。
UpdateServerCheck()
は、60 秒ごとにクエリリクエストが発生したときに確実に最新のデータが Multiplay Hosting に返送されるように、十分な頻度で呼び出す必要があります。
そのための最良の方法の 1 つは、Update
ループ内で呼び出すことです。しかし、特定のイベント (プレイヤーの参加、プレイヤーの退出、ゲームマッチの開始など) が発生したときに呼び出すこともできます。
ノート: currentPlayers
フィールドは常に 0 から始まります。この値は、プレイヤーがゲームサーバーに接続 (またはゲームサーバーから切断) するたびに更新する必要があります。
以下の例は、サーバークエリハンドラーを開始する方法を示しています。
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;
}
}
サーバーイベントにサブスクライブする
SubscribeToServerEventsAsync
メソッドを使用して、ゲームサーバーのサーバーイベントコールバックにサブスクライブします。
以下の例は、OnAllocate
、OnDeallocate
、OnError
などのゲームサーバーイベントコールバックにサブスクライブして処理を行う方法を示しています。
using 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 イベントを処理する
MultiplayEventCallbacks
クラスは、割り当て、割り当て解除、エラー、ゲームサーバーの状態変更などの Multiplay Hosting イベントに応答するためのコールバックを提供します。
以下のコード例は、OnAllocate
、OnDeallocate
、OnError
などのイベントコールバックに応答する方法を示しています。
using 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;
Allocate
コールバックを使用して MultiplayAllocation
イベントに応答します。
割り当て解除
public event Action<MultiplayDeallocation> Deallocate;
Deallocate
コールバックを使用して MultiplayDeallocation
イベントに応答します。
Error
public event Action<MultiplayError> Error;
Error
コールバックを使用して MultiplayError
イベントに応答します。
SubscriptionStateChange
public event Action<MultiplayServerSubscriptionState> SubscriptionStateChanged;
SubscriptionStateChanged
コールバックを使用して MultiplayServerSubscriptionState
イベントに応答します。
Unity エディターを使用したリソースのデプロイ
Multiplay オーサリングモジュール (Multiplay パッケージとともにインストールされる) を使用すると、任意で、リソースのオーサリングと変更を Unity エディター内で直接的に行うことができます。その後、Deployment パッケージ を使用して、Unity エディターからダッシュボードにリソースをアップロードできます。
Unity エディターに存在する Multiplay 設定を使用すると、ユーザーは (クラウド内のバージョンの代わりに) ソース管理を信頼できる唯一の情報源として扱うことができ、ロールバック、二等分、その他の一般的な操作のアクションが簡略化されます。
Multiplay の設定
Unity エディターで Multiplay を使用するには、以下を行ってください。
必要なパッケージをインストールする
エディター内で Multiplay 設定を作成するには、以下のパッケージをインストールします。
- Deployment
- Multiplay:
- Unity 6 以降: マルチプレイヤー
- Unity 2022 LTS 以前: Multiplay
[!NOTE]Unity - マニュアル: Package Manager ウィンドウ を参照し、Unity Package Manager インターフェースについて理解してください。
これらのパッケージをインストールして、使用可能なパッケージのリストに追加するには、以下を行います。
- 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 がない場合:
1. **Create a Unity Project ID** (Unity プロジェクト ID の作成) > **Organizations** (組織) の順に選択し、ドロップダウンメニューから組織を選択します。
2. **Create project ID** (プロジェクト ID を作成) を選択します。
- 既存の Unity プロジェクト ID がある場合:
1. **Use an existing Unity project ID** (既存の Unity プロジェクト ID を使用) を選択します。
2. ドロップダウンメニューから組織とプロジェクトを選択します。
3. **Link project ID** (プロジェクト ID をリンク) を選択します。
Unity プロジェクト ID が表示され、プロジェクトが Unity サービスにリンクされました。また、UnityEditor.CloudProjectSettings.projectId
を使用して Unity エディタースクリプトのプロジェクト ID にアクセスすることもできます。
Unity エディター内でのオーサリング
Multiplay オーサリングモジュールを使用すると、直接 Unity エディター内で、Multiplay 設定の作成、編集、デプロイを行うことができます。
設定の作成
以下のステップに従い、Multiplay オーサリングモジュールを使用して Multiplay 設定を作成します。
- Unity エディターで、Project (プロジェクト) ウィンドウを右クリックし、Create (作成) > Services (サービス) > Multiplay Config (Multiplay 設定) を選択します。
- リソースファイルの名前を指定します。
- Enter を押します。
新しい設定が Project (プロジェクト) ウィンドウに表示されます。また、Deployment (デプロイ) ウィンドウでは、Services (サービス) > Deployment (デプロイ) を選択してアクセスできます。
設定の編集
現在、既存の設定を編集する方法は 1 つです。
- Project (プロジェクト) タブで、既存のリソースをダブルクリックし、任意のテキストエディターを選択して設定を編集します。
リソースファイルのコンテンツ
Deployment (デプロイ) ウィンドウは、リソースを検出し、ファイル拡張子に応じてタイプを割り当てます。
この設定では、内容を記述するための yaml
形式と、.gsh
ファイル拡張子が使用されます。
new_multiplay_config.gsh
の例:
version: 1.0
builds:
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 files
buildConfigurations:
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 server
fleets:
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
この設定ではファイル内で 3 つのコンポーネントが記述されています。
リソースのデプロイ
Multiplay 設定を Deployment (デプロイ) ウィンドウでデプロイできます。詳細については、Deployment パッケージのマニュアル を確認してください。
ビルドそのものに依存しているビルド設定など、設定によっては、他のリソースに対する依存関係があります。
デプロイの際に、最初にビルド、次にビルド設定、その次にフリートをデプロイします。この連鎖のある時点で失敗が発生すると、それに依存している設定のデプロイが停止します。
Deployment (デプロイ) ウィンドウ
Deployment (デプロイ) ウィンドウは、Deployment パッケージのコア機能です。これを使用すると、すべてのサービスが、デプロイニーズに合う 1 つのまとまったインターフェースを持つことができ、クラウドアセットをそれぞれのクラウドサービスにアップロードできます。
詳細については、Deployment パッケージのマニュアル を確認してください。