

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 将 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)。

其他资源 
+ [适用于 Amazon GameLift Servers 的 C\# 服务器 SDK 5.x – 操作](integration-server-sdk5-csharp-actions.md)
+ [获取 Amazon GameLift Servers 开发工具](gamelift-supported.md)

## 安装适用于 Unity 的服务器 SDK
<a name="integration-engines-unity-install"></a>

从这里获取 Unity Amazon GameLift Servers 的开源代码[GitHub](https://github.com/amazon-gamelift/amazon-gamelift-plugin-unity)。该存储库的自述文件包含先决条件和安装说明。

## 设置 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。记下 ARN，稍后您将用到它。

1. 将您的工作站注册为新 Anywhere 实例集内的计算。为您的工作站提供唯一的计算名称并指定 IP 地址。如果成功，此请求将以 WebSocket URL 的形式返回服务 SDK 端点。记下 ARN，稍后您将用到它。

1. 为您的工作站计算生成身份验证令牌。这种短暂的身份验证包括令牌和到期日期。您的游戏服务器使用其来验证与 Amazon GameLift Servers 服务的通信。将身份验证存储在您的工作站计算机上，以便正在运行的游戏服务器进程可以对其进行访问。

## 将 Amazon GameLift Servers 服务器代码添加到 Unity 项目中
<a name="integration-engines-unity-code"></a>

您的游戏服务器通过与 Amazon GameLift Servers 服务通信来接收指令并报告持续状态。为此，您需要添加使用 Amazon GameLift Servers 服务器 SDK 的游戏服务器代码。

提供的代码示例说明了所需的基本集成元素。它使用 `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)。有关此代码中使用的软件开发工具包 操作和数据类型的更多信息，请阅读[适用于 Amazon GameLift Servers 的 C\# 服务器 SDK 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 操作的更多信息，请参阅[适用于 Amazon GameLift Servers 的 C\# 服务器 SDK 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 Servers Anywhere 为迭代开发做好准备](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)
  + [适用于 Amazon GameLift Servers 的 C\+\+（Unreal）服务器 SDK 5.x – 操作](integration-server-sdk5-unreal-actions.md)
+ 自定义您的游戏客户端组件，以请求游戏会话、接收连接信息并直接连接到游戏服务器进行游戏。请参阅以下主题获取指导：
  + [集成 Amazon GameLift Servers 游戏客户端功能](gamelift-sdk-client-api.md)