기술 자료

지원

Multiplay Hosting

Multiplay Hosting

Unity용 Multiplay Hosting SDK

Integrate Multiplay Hosting functionality into your Unity game server.
읽는 시간 5분최근 업데이트: 10시간 전

Unity용 Multiplay Hosting SDK에는 게임에서 Multiplay Hosting 스케일링과 게임 서버 서비스를 활용하는 데 필요한 모든 기능이 담겨 있습니다.
Unity.Services.Multiplay
가 Multiplay 서비스와 상호 작용하기 위한 기본 네임스페이스입니다.

요구 사항 및 제한 사항

Unity용 Multiplay Hosting SDK는 Unity 에디터 버전 2020.3 이상에서 작동합니다.

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
문자열할당 ID입니다.
queryPort
ushort서버 쿼리 프로토콜 포트 번호입니다.
port
ushort게임 세션의 연결 포트입니다. 게임 클라이언트가 게임 세션에 연결하기 위해 사용할 수 있는 포트 번호입니다.
serverLogDirectory
문자열게임 서버가 로그 파일을 저장하는 디렉토리입니다.
다음 예시 코드는
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
문자열서버 이름입니다.
gameType
문자열서버가 실행 중인 게임 유형의 이름 또는 식별자입니다.
buildId
문자열게임의 버전입니다.
map
문자열서버가 게임에서 실행 중인 맵 또는 월드입니다.
port
ushort게임 클라이언트가 게임 서버에 연결하기 위해 사용할 수 있는 포트 번호입니다.
Multiplay Hosting은
StartServerQueryHandlerAsyncparameters
를 사용하여 서버 쿼리 핸들러를 초기화합니다.
서버 쿼리 핸들러를 초기화하고 나면 이 호출로 제공된
IServerCheckManager
인스턴스를 사용하여 언제든지 값을 업데이트할 수 있습니다. 변경 사항을 적용하려면
UpdateServerCheck()
를 호출해야 합니다. 게임 서버 변수가 변경되면
UpdateServerCheck()
를 호출하십시오. 자세한 내용은 SQP를 참고하시기 바랍니다.
다음 예시는 서버 쿼리 핸들러를 시작하는 방법을 보여 줍니다.
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; } }}

Allocate

public event Action<MultiplayAllocation> Allocate;
Allocate
콜백을 사용하여
MultiplayAllocation
이벤트에 응답합니다.

Deallocate

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 Authoring 모듈을 사용하면 필요에 따라 Unity 에디터에서 직접 리소스를 저작하고 수정할 수 있습니다. 그런 다음 Deployment 패키지를 사용하여 Unity 에디터에서 Unity Dashboard에 리소스를 업로드할 수 있습니다. Unity 에디터 내에 있는 Multiplay 구성을 사용하면 사용자는 소스 컨트롤을 클라우드에 있는 버전이 아닌 SSOT(single source of truth)로 취급하여 롤백, 이분화, 기타 일반적인 연산 등의 작업을 간소화할 수 있습니다.

Multiplay 설정

Unity 에디터에서 Multiplay를 사용하려면 다음을 수행합니다.
  1. SDK 설치
  2. Unity 에디터에 프로젝트 연결

필수 패키지 설치

에디터에서 Multiplay 구성을 생성하려면 다음 패키지를 설치합니다.
  • Deployment
  • Multiplay:
    • Unity 6 이상: Multiplayer
    • Unity 2022 LTS 이하: Multiplay
위 패키지를 설치한 후 다음 단계에 따라 사용 가능한 패키지 목록에 패키지를 추가합니다.
  1. Unity 에디터에서 Window > Package Manager를 선택합니다.
  2. + > Install package by name을 선택합니다.
  3. com.unity.services.deployment
    를 입력합니다.
  4. Install을 선택합니다.
  5. Multiplay에도 같은 단계를 반복합니다.
    • Unity 6 이상:
      com.unity.services.multiplayer
    • Unity 2022 LTS 이하:
      com.unity.services.multiplay

프로젝트 연결

Unity Gaming Services 프로젝트를 Unity 에디터와 연결합니다. Unity Dashboard에서 UGS 프로젝트 ID를 확인할 수 있습니다.
  1. Unity 에디터에서 Edit > Project Settings > Services를 선택합니다.
  2. 프로젝트를 연결합니다.
  • 프로젝트에 Unity 프로젝트 ID가 없는 경우 다음 단계를 진행합니다.
  1. Create a Unity Project ID > Organizations를 선택한 다음 드롭다운 메뉴에서 조직을 선택합니다.
  2. Create project ID를 선택합니다.
  • Unity 프로젝트 ID가 있는 경우 다음 단계를 진행합니다.
  1. Use an existing Unity project ID를 선택합니다.
  2. 드롭다운 메뉴에서 조직과 프로젝트를 선택합니다.
  3. Link project ID를 선택합니다.
Unity 프로젝트 ID가 표시되고 이제 Unity 서비스에 프로젝트가 연결됩니다.
UnityEditor.CloudProjectSettings.projectId
를 사용하여 Unity 에디터 스크립트에서 프로젝트 ID에 액세스할 수도 있습니다.

Unity 에디터에서 저작

Multiplay Authoring 모듈을 사용하면 Unity 에디터 내에서 바로 Multiplay 구성을 생성, 편집, 배포할 수 있습니다.

구성 생성

Multiplay Authoring 모듈을 사용하여 Multiplay 구성을 생성하려면 다음 단계를 수행합니다.
  1. Unity 에디터에서 프로젝트(Project) 창을 오른쪽 클릭하고 Create > Services > Multiplay Config를 선택합니다.
  2. 리소스 파일의 이름을 지정합니다.
  3. Enter 키를 누릅니다.
이제 프로젝트 창과 Services > Deployment를 선택하여 액세스할 수 있는 Deployment 창에서 새로 생성한 구성을 볼 수 있습니다.

구성 편집

현재 한 가지 메서드로 기존 구성을 편집할 수 있습니다.
  • Project 탭에서 기존 리소스를 더블 클릭한 다음 텍스트 에디터를 선택하여 구성을 편집합니다.

리소스 파일 콘텐츠

Deployment 창에서 리소스를 확인하고 파일 확장자에 따라 유형을 할당합니다. 구성은
yaml
형식을 사용하여 콘텐츠와
.gsh
파일 확장자를 설명합니다.
new_multiplay_config.gsh
의 예시:
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
구성은 파일 내 3개의 구성 요소를 설명합니다.

리소스 배포

Deployment 창을 통해 Multiplay 구성을 배포할 수 있습니다. 자세한 내용은 Deployment 패키지 매뉴얼을 참고하십시오. 일부 구성은 다른 리소스와 종속 관계에 있습니다. 예를 들어, 빌드 구성은 빌드 자체에 종속됩니다. 배포할 때는 빌드를 먼저 배포한 다음 빌드 구성과 플릿을 순서대로 배포합니다. 체인의 한 지점에서 실패가 발생하면 종속된 구성의 배포가 중단됩니다.

Deployment 창

Deployment 창은 Deployment 패키지의 주요 기능입니다. Deployment 창을 사용하면 단일 통합 인터페이스를 사용하여 배포 요구 사항에 맞춰 모든 서비스에서 배포할 수 있으며, 클라우드 에셋을 각 클라우드 서비스에 업로드할 수 있습니다. 자세한 내용은 Deployment 패키지 매뉴얼을 참고하십시오.