

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon GameLift Servers 整合至 Unity 專案
<a name="integration-engines-unity-using"></a>

了解如何將適用於 Unity 的 Amazon GameLift Servers SDK 整合到您的遊戲專案中，以存取完整的伺服器 SDK 功能集。

**秘訣**  
若要加快部署速度，請嘗試 Unity Amazon GameLift Servers的獨立外掛程式。它提供引導式 UI 工作流程，以最少的設定快速部署遊戲伺服器，因此您可以嘗試執行中的遊戲元件。請參閱 [Amazon GameLift Servers Unity 的外掛程式 （伺服器 SDK 5.x)](unity-plug-in.md)。

其他資源：
+ [適用於 -- 動作的 C\# 伺服器 SDK Amazon GameLift Servers 5.x](integration-server-sdk5-csharp-actions.md)
+ [取得Amazon GameLift Servers開發工具](gamelift-supported.md)

## 安裝適用於 Unity 的伺服器 SDK
<a name="integration-engines-unity-install"></a>

從 [GitHub](https://github.com/amazon-gamelift/amazon-gamelift-plugin-unity) 取得 Unity Amazon GameLift Servers 的開放原始碼。儲存庫的讀我檔案包含先決條件和安裝指示。

## 設定 Amazon GameLift Servers Anywhere 機群進行測試
<a name="integration-engines-unity-fleet"></a>

您可以將開發工作站設定為 Amazon GameLift Servers Anywhere 託管機群，以反覆測試Amazon GameLift Servers整合。透過此設定，您可以在工作站上啟動遊戲伺服器程序、將玩家加入或配對請求傳送至 Amazon GameLift Servers 以啟動遊戲工作階段，並將用戶端連線至新的遊戲工作階段。透過將自己的工作站設定為託管伺服器，您可以監控與 的遊戲整合的各個層面Amazon GameLift Servers。

如需設定工作站的指示，請參閱 [使用 Amazon GameLift Servers Anywhere 設定本機測試](integration-testing.md) 以完成下列步驟：

1. 為您的工作站建立自訂位置。

1. 使用新的自訂位置建立 Amazon GameLift Servers Anywhere 機群。如果成功，此請求會傳回機群 ID。請記下此值，因為您稍後會需要它。

1. 在新的 Anywhere 機群中將工作站註冊為運算。提供唯一的運算名稱，並指定工作站的 IP 地址。如果成功，此請求會以 WebSocket URL 的形式傳回服務 SDK 端點。請記下此值，因為您稍後會需要它。

1. 為您的工作站運算產生身分驗證字符。此短期身分驗證包含權杖和過期日期。您的遊戲伺服器會使用它來驗證與 Amazon GameLift Servers服務的通訊。將身分驗證存放在工作站運算上，以便您執行的遊戲伺服器程序可以存取。

## 將Amazon GameLift Servers伺服器程式碼新增至 Unity 專案
<a name="integration-engines-unity-code"></a>

您的遊戲伺服器會與 Amazon GameLift Servers服務通訊，以接收指示並報告持續狀態。若要達成此目的，您可以新增使用伺服器 SDK 的遊戲Amazon GameLift Servers伺服器程式碼。

提供的程式碼範例說明基本的必要整合元素。它使用 `MonoBehavior`來說明使用 進行簡單的遊戲伺服器初始化Amazon GameLift Servers。此範例假設遊戲伺服器在 Amazon GameLift Servers Anywhere 機群上執行以進行測試。它包含程式碼以：
+ 初始化 Amazon GameLift Servers API 用戶端。此範例使用 版本`InitSDK()`搭配 Anywhere 機群和運算的伺服器參數。使用 WebSocket URL、機群 ID、運算名稱 （主機 ID) 和身分驗證字符，如上一個主題 所定義[設定 Amazon GameLift Servers Anywhere 機群進行測試](#integration-engines-unity-fleet)。
+ 實作回呼函數來回應來自 Amazon GameLift Servers服務的請求，包括 `OnStartGameSession`、 `OnProcessTerminate`和 `onHealthCheck`。
+ 使用指定的連接埠呼叫 ProcessReady()，以在程序準備好託管遊戲工作階段時通知Amazon GameLift Servers服務。

提供的範例程式碼會建立與服務的通訊Amazon GameLift Servers。它也會實作一組回呼函數，以回應來自 Amazon GameLift Servers服務的請求。如需每個函數和程式碼功能的詳細資訊，請參閱[初始化伺服器程序](https://docs.aws.amazon.com//gameliftservers/latest/developerguide/gamelift-sdk-server-api.html#gamelift-sdk-server-initialize)。如需此程式碼中使用的 SDK 動作和資料類型的詳細資訊，請參閱 [適用於 -- 動作的 C\# 伺服器 SDK Amazon GameLift Servers 5.x](integration-server-sdk5-csharp-actions.md)。

範例程式碼示範如何新增所需的功能，如[Amazon GameLift Servers新增至遊戲伺服器](https://docs.aws.amazon.com//gameliftservers/latest/developerguide/gamelift-sdk-server-api.html)中所述。如需伺服器 SDK 動作的詳細資訊，請參閱 [適用於 -- 動作的 C\# 伺服器 SDK Amazon GameLift Servers 5.x](integration-server-sdk5-csharp-actions.md)。

### 整合範例程式碼
<a name="w2aab9c11c11b9c19c15c13b1"></a>

```
using System.Collections.Generic;
using Aws.GameLift.Server;
using UnityEngine;

public class ServerSDKManualTest : MonoBehaviour
{    
    //This example is a simple integration that initializes a game server process 
    //that is running on an Amazon GameLift Servers Anywhere fleet.
    void Start()
    {        
        //Identify port number (hard coded here for simplicity) the game server is listening on for player connections
        var listeningPort = 7777;

        //WebSocketUrl from RegisterHost call
        var webSocketUrl = "wss://us-west-2.api.amazongamelift.com";

        //Unique identifier for this process
        var processId = "myProcess";

        //Unique identifier for your host that this process belongs to
        var hostId = "myHost";

        //Unique identifier for your fleet that this host belongs to
        var fleetId = "myFleet";

        //Authorization token for this host process
        var authToken = "myAuthToken";

        //Server parameters are required for an Amazon GameLift Servers Anywhere fleet.
        //They are not required for an Amazon GameLift Servers managed EC2 fleet.
        ServerParameters serverParameters = new ServerParameters(
            webSocketUrl,
            processId,
            hostId,
            fleetId,
            authToken);

        //InitSDK establishes a local connection with an Amazon GameLift Servers agent 
        //to enable further communication.
        var initSDKOutcome = GameLiftServerAPI.InitSDK(serverParameters);        
        if (initSDKOutcome.Success)
        {
            //Implement callback functions
            ProcessParameters processParameters = new ProcessParameters(
            //Implement OnStartGameSession callback
                (gameSession) => {
                    //Amazon GameLift Servers sends a game session activation request to the game server 
                    //with game session object containing game properties and other settings.
                    //Here is where a game server takes action based on the game session object.
                    //When the game server is ready to receive incoming player connections, 
                    //it invokes the server SDK call ActivateGameSession().
                    GameLiftServerAPI.ActivateGameSession();
                },
                (updateGameSession) => {
                    //Amazon GameLift Servers sends a request when a game session is updated (such as for 
                    //FlexMatch backfill) with an updated game session object. 
                    //The game server can examine matchmakerData and handle new incoming players.
                    //updateReason explains the purpose of the update.
                },
                () => {
                    //Implement callback function OnProcessTerminate
                    //Amazon GameLift Servers invokes this callback before shutting down the instance hosting this game server.
                    //It gives the game server a chance to save its state, communicate with services, etc., 
                    //and initiate shut down. When the game server is ready to shut down, it invokes the 
                    //server SDK call ProcessEnding() to tell Amazon GameLift Servers it is shutting down.
                    GameLiftServerAPI.ProcessEnding();
                }, 
                () => {
                    //Implement callback function OnHealthCheck
                    //Amazon GameLift Servers invokes this callback approximately every 60 seconds.
                    //A game server might want to check the health of dependencies, etc.
                    //Then it returns health status true if healthy, false otherwise.
                    //The game server must respond within 60 seconds, or Amazon GameLift Servers records 'false'.
                    //In this example, the game server always reports healthy.
                    return true;
                },
                //The game server gets ready to report that it is ready to host game sessions
                //and that it will listen on port 7777 for incoming player connections.
                listeningPort, 
                new LogParameters(new List<string>()
                {
                    //Here, the game server tells Amazon GameLift Servers where to find game session log files.
                    //At the end of a game session, Amazon GameLift Servers uploads everything in the specified 
                    //location and stores it in the cloud for access later.
                    "/local/game/logs/myserver.log"
                }));

            //The game server calls ProcessReady() to tell Amazon GameLift Servers it's ready to host game sessions.
            var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParameters);
            if (processReadyOutcome.Success)
            {
                print("ProcessReady success.");
            }
            else
            {
                print("ProcessReady failure : " + processReadyOutcome.Error.ToString());
            }
        }
        else
        {
            print("InitSDK failure : " + initSDKOutcome.Error.ToString());
        }
    }  

    void OnApplicationQuit()
    {
        //Make sure to call GameLiftServerAPI.ProcessEnding() and GameLiftServerAPI.Destroy() before terminating the server process.
        //These actions notify Amazon GameLift Servers that the process is terminating and frees the API client from memory. 
        GenericOutcome processEndingOutcome = GameLiftServerAPI.ProcessEnding();
        GameLiftServerAPI.Destroy();
        if (processEndingOutcome.Success)
        {
            Environment.Exit(0);
        }
        else
        {
            Console.WriteLine("ProcessEnding() failed. Error: " + processEndingOutcome.Error.ToString());
            Environment.Exit(-1);  
        }
    }
}
```

## 後續步驟
<a name="integration-engines-unity-additional-resources"></a>

現在您已使用 託管所需的最低功能準備遊戲伺服器組建Amazon GameLift Servers，請考慮下列可能的後續步驟：
+ 為 和測試和開發部署整合的遊戲伺服器。使用 Anywhere 機群，您可以將本機機器設定為託管資源，並使用它來測試遊戲伺服器和遊戲用戶端連線。對於雲端託管，請將遊戲伺服器部署到受管 EC2 或受管容器機群。如需指引，請參閱這些主題：
  + [使用 Amazon GameLift ServersAnywhere 設定反覆開發](integration-dev-iteration.md)
  + [Amazon GameLift Servers Anywhere 機群](fleets-intro-anywhere.md)
  + [Amazon GameLift Servers 受管 EC2 機群](fleets-intro-managed.md)
  + [Amazon GameLift Servers 受管容器機群](fleets-intro-containers.md)
+ 新增選用功能，自訂您的遊戲伺服器整合。例如，您可能想要新增具有唯一玩家 IDs玩家工作階段、設定配對回填，或管理遊戲伺服器對其他 AWS 資源 （例如資料庫或內容儲存服務） 的存取。如需指引，請參閱這些主題：
  + [使用伺服器 SDK 將 Amazon GameLift Servers新增至您的遊戲伺服器](gamelift-sdk-server-api.md)
  + [適用於 -- 動作的 C\+\+ (Unreal) 伺服器 SDK Amazon GameLift Servers 5.x](integration-server-sdk5-unreal-actions.md)
+ 自訂您的遊戲用戶端元件以請求遊戲工作階段、接收連線資訊，並直接連線至遊戲伺服器以玩遊戲。如需指引，請參閱這些主題：
  + [整合Amazon GameLift Servers遊戲用戶端功能](gamelift-sdk-client-api.md)