> For the complete documentation index, see [llms.txt](https://docs.edgegap.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.edgegap.com/ko/docs/sample-projects/unity-netcodes/unity-netcode-on-edgegap.md).

# Unity NGO

NGO Boss Room 샘플을 따라 빌드부터 실시간 배포까지 진행하며, Edgegap에서 Unity Netcode for GameObjects 프로젝트를 호스팅하세요.

다음의 기법을 사용해 Edgegap에서 Unity 프로젝트를 호스팅하는 방법을 살펴보세요 [NGO Boss Room 샘플](https://unity.com/demos/small-scale-coop-sample).

{% hint style="info" %}
이 샘플은 **Unity Gaming Services(UGS)가 전혀 필요하지 않습니다**, Multiplay 또는 Relays 없이 실행할 수 있습니다.
{% endhint %}

{% embed url="<https://youtu.be/8Qi-wXswjkw>" %}

## ✔️ 준비

시작하기 전에 다음이 필요합니다:

* [Unity 6](https://unity.com/releases/unity-6) - Unity Hub를 사용해 다운로드,
* [Unity NGO \[Netcode for Game Objects\] Boss Room 샘플 프로젝트](https://github.com/edgegap/netcode-game-sample-unity-ngo-bossroom) (Edgegap용으로 수정됨).

## ⚡ 배포 및 연결

### 1. Edgegap에 서버 배포

☑️ 시작하려면 다음이 필요합니다 [Edgegap에 무료 계정을 만드세요](https://app.edgegap.com/auth/register). 신용카드는 필요 없습니다.

☑️ [애플리케이션에 대한 새 앱 버전 만들기](https://app.edgegap.com/application-management/applications/unity-ngo-bossroom-sample/versions/create), NGO Boss Room Sample을 선택하세요.

☑️ [NGO Boss Room Sample 앱 버전으로 서버를 배포합니다](https://app.edgegap.com/deployment-management/deployments/list).

☑️ [새 배포의 세부 정보를 열고](https://app.edgegap.com/deployment-management/deployments/list) 고유한 일회성 연결 정보를 확인하세요:

* **외부 포트**, 예를 들어 `30854` (무작위로 선택됨).

☑️ Logs 탭으로 이동하여 (CTRL+F) 고유한 일회성 연결 정보를 찾으세요:

* `ARBITRIUM_PUBLIC_IP` , 예: IPv4: `172.234.244.38` .

✅ 이제 다음 단계로 진행할 수 있습니다.

### 2. 에디터에서 연결

☑️ Unity에서 새 프로젝트를 여세요.

☑️ 다음 씬이 열렸는지 확인하세요: `Assets/Scenes/MainMenu.unity`.

☑️ ▶️ Play 버튼을 눌러 게임 클라이언트를 시작하세요:

* 누르세요 **직접 IP로 시작** 버튼,
* 탭을 선택하세요 **IP로 참가.**

☑️ 이전 단계의 연결 정보를 입력하세요.

☑️ 누르세요 **JOIN** 버튼을 눌러 서버에 연결하세요.

☑️ 다음을 사용해 두 번째 가상 플레이어를 연결하세요. [Multiplayer Play Mode](https://docs-multiplayer.unity3d.com/mppm/current/about/) 또는 [ParrelSync](https://github.com/VeriorPies/ParrelSync).

🙌 Edgegap에서 첫 배포를 축하합니다!

## 🎯 매치메이킹(선택 사항)

플레이어를 다음과 매칭: [Edgegap Matchmaker](https://docs.edgegap.com/ko/learn/matchmaking.md) - 플레이어를 그룹화하고, Edgegap이 그들 근처에서 서버를 시작하며, 모든 클라이언트가 자동으로 연결됩니다. 매치메이킹은 기본적으로 비활성화되어 있으므로 직접 연결이 작동하면 활성화하세요.

{% hint style="success" %}
매치메이킹 스크립트는 다음 위치에 있습니다: `Assets/Edgegap/` 그리고 런타임에 스스로 추가되므로 **Boss Room의 씬과 프리팹은 수정되지 않습니다**. 자세한 내용은 [EDGEGAP.md](https://github.com/edgegap/netcode-game-sample-unity-ngo-bossroom/blob/main/EDGEGAP.md) 파일 및 명령줄 옵션의 전체 목록을 참조하세요.
{% endhint %}

### 1. 매치메이커 만들기

☑️ 다음을 설정합니다 `application.name` 및 `application.version` 샘플의 애플리케이션과 버전에 `matchmaker-config.json`.

설정에는 하나의 `캐주얼` 2\~8명의 플레이어용 프로필입니다. 가능하면 최대 8명까지 채우며, 그 [확장](https://docs.edgegap.com/ko/learn/matchmaking/matchmaker-in-depth.md#rule-expansion) 을 15초로 설정하면 더 적은 인원(최소 2명)으로 시작할 수 있습니다.

☑️ 다음을 엽니다 [Matchmaker](https://app.edgegap.com/matchmaker-management-v2/matchmakers/list) 페이지에서 클릭합니다 **매치메이커 만들기**, 업로드한 뒤 `matchmaker-config.json`, 그런 다음 클릭합니다 **만들기 및 시작**.

☑️ 매치메이커의 다음 항목을 복사합니다 **API URL** 및 **인증 토큰**.

✅ 이제 다음 단계로 진행할 수 있습니다.

### 2. 매치 찾기

☑️ 선택하세요 `Assets/Edgegap/Resources/EdgegapSettings.asset` 그리고 체크하세요 **Edgegap 매치메이커 사용**.

☑️ 다음을 붙여넣으세요: **API URL** 를 다음에 복사하세요: **매치메이커 URL** 및 **인증 토큰** 를 다음에 복사하세요: **매치메이커 인증 토큰**.

{% hint style="danger" %}
**API 토큰은 계정에 무제한 접근 권한을 제공하므로 게임 클라이언트에 Edgegap API 엔드포인트를 통합하지 마세요. 다음을 참조하세요** [통합](https://docs.edgegap.com/ko/docs/api/integration.md) **안전한 클라이언트용 API 엔드포인트와 기능은 다음을 참조하세요.**
{% endhint %}

{% hint style="info" %}
매치메이킹 인증 토큰은 매치메이커 전용 범위이므로 게임 클라이언트에 포함해 배포해도 안전합니다.
{% endhint %}

☑️ 클라이언트를 다시 빌드하고 두 번 시작하세요. 한 PC에서 두 개의 복사본을 실행하려면 각각에 고유한 프로필을 지정하세요: `Game.exe -AuthProfile p1` 및 `Game.exe -AuthProfile p2`.

☑️ 클릭 **매치 찾기** 두 클라이언트 모두에서 메인 메뉴 왼쪽 패널에서.

상태는 검색, 매치 발견, 참가 순으로 진행되며, 두 플레이어는 같은 서버의 캐릭터 선택 화면에 도착합니다. 영웅을 선택하고 **준비** 를 눌러 함께 던전에 입장하세요.

🙌 Edgegap에서 첫 번째 매치메이킹 배포를 축하합니다!

{% hint style="warning" %}
매치메이커 설정에 확장 단계를 포함하세요. 없으면 매치메이커는 [부분 매치](https://docs.edgegap.com/ko/learn/matchmaking/matchmaker-in-depth.md#partial-matches) 를 티켓 만료 시(5분)만 만듭니다.
{% endhint %}

## 🛑 서버 자동 중지

매치메이킹 여부와 관계없이, 서버는 자체 배포를 중지하여 유휴 서버에 비용이 들지 않게 합니다:

* 120초 안에 아무도 참가하지 않으면,
* 마지막 플레이어가 나간 후 30초 뒤에.

다음으로 이 타임아웃을 변경하세요: **첫 번째 플레이어 타임아웃(초)** 및 **빈 서버 타임아웃(초)** 의 `EdgegapSettings.asset`. 중지 요청이 실패하면 대신 서버가 종료됩니다.

## ✏️ 서버 빌드 커스터마이징

{% hint style="success" %}
참조 [Unity](https://docs.edgegap.com/ko/unity.md) 다음으로 **서버를 빌드하고 커스터마이즈하는 방법을 알아보세요**.
{% endhint %}

### 전용 서버로 실행

이 샘플을 전용 서버로 실행하기 위해 다음 변경 사항을 적용했습니다:

{% tabs %}
{% tab title="서버 초기화" %}
새 스크립트(다음에 추가됨: `MainMenu` 씬의 새 빈 `GameObject`):

<pre class="language-csharp" data-title="Assets/Scripts/EdgegapServerStarter.cs" data-line-numbers data-collapsed-line-count="10"><code class="lang-csharp">using System;
using System.Collections;
using System.Collections.Generic;
using Unity.BossRoom.ConnectionManagement;
using UnityEngine;

namespace Unity.Multiplayer.Samples.BossRoom
{
    public class EdgegapServerStarter : MonoBehaviour
    {
        // 첫 번째 프레임 업데이트 전에 호출됩니다
        void Start()
        {
            if (Application.isBatchMode)
            {
                ConnectionManager connectionManager = GameObject.Find("ConnectionManager").GetComponent&#x3C;ConnectionManager>();
<strong>                string internalPortAsStr = Environment.GetEnvironmentVariable($"<a data-footnote-ref href="#user-content-fn-1">ARBITRIUM_PORT_GAMEPORT_INTERNAL</a>");
</strong>
                ushort port;
                if (internalPortAsStr == null)
                {
                    // Edgegap이 아닌 경우(로컬 실행 또는 Docker 실행): EdgegapSettings.ListenPort 또는 -edgegapListenPort를 사용하세요.
                    port = EdgegapBootstrap.Settings != null ? EdgegapBootstrap.Settings.ListenPort : (ushort)9998;
                    Debug.LogWarning($"No ARBITRIUM_PORT_GAMEPORT_INTERNAL, not on Edgegap: listening on port {port}.");
                }
                else if (!ushort.TryParse(internalPortAsStr, out port))
                {
                    throw new Exception($"Could not find port mapping, make sure your app version port name matches with \"{portMapName}\"");
                }

                Debug.Log($"Edgegap Server | Starting server on 0.0.0.0:{port}.");
<strong>                connectionManager.StartHostIp("<a data-footnote-ref href="#user-content-fn-2">SERVER</a>", "0.0.0.0", port);
</strong>            }
        }
    }
}
</code></pre>

{% endtab %}

{% tab title="연결 관리" %}
수정된 파일:

<pre class="language-csharp" data-title="Assets/Scripts/ConnectionManagement/ConnectionMethod.cs" data-collapsed-line-count="10"><code class="lang-csharp"><strong>116        public override async Task SetupHostConnectionAsync()
</strong>117        {
<strong>118            <a data-footnote-ref href="#user-content-fn-3">//SetConnectionPayload(GetPlayerId(), m_PlayerName); // 호스트도 클라이언트이므로, 호스트에 대해서도 연결 페이로드를 설정해야 합니다</a>
</strong>119            var utp = (UnityTransport)m_ConnectionManager.NetworkManager.NetworkConfig.NetworkTransport;
120            utp.SetConnectionData(m_Ipaddress, m_Port);
121        }
</code></pre>

<pre class="language-csharp" data-title="Assets/Scripts/ConnectionManagement/ConnectionState/StartingHostState.cs" data-collapsed-line-count="10"><code class="lang-csharp"><strong>66        async void StartHost()
</strong>67        {
              ...

72                // NGO의 StartHost가 모든 것을 시작합니다
<strong>--                <a data-footnote-ref href="#user-content-fn-3">//if (!m_ConnectionManager.NetworkManager.StartHost())</a>
</strong><strong>73                <a data-footnote-ref href="#user-content-fn-4">if (!m_ConnectionManager.NetworkManager.StartServer())</a>
</strong>74                {
75                    StartHostFailed();
76                }

              ...
</code></pre>

<pre class="language-csharp" data-title="Assets/Scripts/Gameplay/GameplayObjects/Character/ClientCharacter.cs" data-collapsed-line-count="10"><code class="lang-csharp"><strong>112        public override void OnNetworkSpawn()
</strong>113        {
               ...

125            m_ServerCharacter.IsStealthy.OnValueChanged += OnStealthyChanged;
126            m_ServerCharacter.MovementStatus.OnValueChanged += OnMovementStatusChanged;
<strong>127            <a data-footnote-ref href="#user-content-fn-3">//OnMovementStatusChanged(MovementStatus.Normal, m_ServerCharacter.MovementStatus.Value);</a>
</strong> 
               ...
</code></pre>

{% endtab %}

{% tab title="에디터/서버 호환성" %}
파일을 수정하세요:

<pre class="language-csharp" data-title="Assets/Scripts/ConnectionManagement/ConnectionState/HostingState.cs" data-collapsed-line-count="10"><code class="lang-csharp"><strong>148        ConnectStatus GetConnectStatus(ConnectionPayload connectionPayload)
</strong>149        {
               ...
                
<strong>155            <a data-footnote-ref href="#user-content-fn-5">//if (connectionPayload.isDebug != Debug.isDebugBuild)</a>
</strong><strong>156            //{
</strong><strong>157            //    return ConnectStatus.IncompatibleBuildType;
</strong><strong>158            //}
</strong>
               ...
</code></pre>

{% endtab %}
{% endtabs %}

[^1]: Edgegap의 기본 포트 이름은 'gameport'입니다

[^2]: 서버의 플레이어 이름은 어떤 값이든 될 수 있습니다

[^3]: p2p 전용 ⇒ 이 부분을 주석 처리

[^4]: 대신 전용 서버로 시작

[^5]: 에디터 호환성 ⇒ 이 부분을 주석 처리
