

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

# 将 Amazon GameLift Servers 与 Unity 游戏客户端项目集成
<a name="integration-unity-client-sdk4"></a>

**注意**  
本主题提供了适用于 Unity 的 Amazon GameLift Servers 插件的早期版本相关信息。版本 1.x 使用适用于 Amazon GameLift Servers 4.x 或更早版本的服务器 SDK。有关插件最新版本（使用服务器 SDK 5.x 并支持 Amazon GameLift Servers Anywhere 和托管式容器托管等新功能）的文档，请参阅[Amazon GameLift Servers适用于 Unity 的插件（服务器 SDK 5.x）](unity-plug-in.md)。

本主题可帮助您设置游戏客户端，以通过后端服务连接到 Amazon GameLift Servers 托管的游戏会话。Amazon GameLift Servers APIs 用于发起配对、请求游戏会话放置等。

向后端服务项目添加代码，以允许与 Amazon GameLift Servers 服务进行通信。后端服务处理游戏客户端与该 GameLift 服务的所有通信。有关后端服务的更多信息，请参阅。

 后端服务器处理以下游戏客户端任务：
+ 自定义玩家身份验证。
+ 从 Amazon GameLift Servers 服务请求有关活动游戏会话的信息。
+ 创建新的游戏会话。
+ 将玩家加入到现有游戏会话。
+ 将玩家从现有游戏会话中移除。

**Topics**
+ [先决条件](#integration-unity-client-sdk4-prereq)
+ [初始化游戏客户端](#integration-unity-client-sdk4-initialize)
+ [按照特定的实例集创建游戏会话](#integration-unity-client-sdk4-game-session)
+ [向游戏会话中添加玩家](#integration-unity-client-sdk4-add-player)
+ [从游戏会中移除玩家](#integration-unity-client-sdk4-remove-player)

## 先决条件
<a name="integration-unity-client-sdk4-prereq"></a>

在使用 Amazon GameLift Servers 客户端设置游戏服务器通信前，请完成以下任务：
+ [设置 AWS 用户账户](setting-up-aws-login.md)
+ [安装并设置插件](unity-plug-in-sdk4.md#unity-plug-in-sdk4-install)
+ [将 Amazon GameLift Servers 与 Unity 游戏服务器项目集成](integration-unity-server-sdk4.md)
+ [为 Amazon GameLift Servers 部署托管实例集](fleets-intro.md)

## 初始化游戏客户端
<a name="integration-unity-client-sdk4-initialize"></a>

**注意**  
本主题指的是适用于 Unity 的 Amazon GameLift Servers 插件版本 1.0.0（使用服务器 SDK 4.x 或更早版本）。

添加用于初始化游戏客户端的代码。启动时运行此代码，这是其他 Amazon GameLift Servers 功能的必要条件。

1. 初始化 `AmazonGameLiftClient`。使用默认客户端配置或自定义配置调用 `AmazonGameLiftClient`。有关如何配置客户端的更多信息，请参阅[设置 Amazon GameLift Servers API](gamelift-sdk-client-api.md#gamelift-sdk-client-api-initialize)。

1. 为每个玩家生成唯一的玩家 ID 来连接到游戏会话。有关更多信息，请参阅 [生成玩家 ID](player-sessions-player-identifiers.md)。

   以下示例显示了如何设置Amazon GameLift Servers客户端。

   ```
   public class GameLiftClient
   {
       private GameLift gl;
       //A sample way to generate random player IDs. 
       bool includeBrackets = false;
       bool includeDashes = true;
       string playerId = AZ::Uuid::CreateRandom().ToString<string>(includeBrackets, includeDashes);
   		
       
       private Amazon.GameLift.Model.PlayerSession psession = null;
       public AmazonGameLiftClient aglc = null;
   
       public void CreateGameLiftClient()
       {
           //Access Amazon GameLift Servers service by setting up a configuration. 
           //The default configuration specifies a location. 
           var config = new AmazonGameLiftConfig();
           config.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
      
           CredentialProfile profile = null;
           var nscf = new SharedCredentialsFile();
           nscf.TryGetProfile(profileName, out profile);
           AWSCredentials credentials = profile.GetAWSCredentials(null); 
           //Initialize Amazon GameLift Servers Client with default client configuration.
           aglc = new AmazonGameLiftClient(credentials, config); 
           
       }
   }
   ```

## 按照特定的实例集创建游戏会话
<a name="integration-unity-client-sdk4-game-session"></a>

**注意**  
本主题指的是适用于 Unity 的 Amazon GameLift Servers 插件版本 1.0.0（使用服务器 SDK 4.x 或更早版本）。

添加用于在已部署的实例集中启动新游戏会话并使其可供玩家接入的代码。在 Amazon GameLift Servers 创建了新游戏会话并返回 `GameSession` 后，便可以向其中添加玩家。
+ 申请新游戏会话。
  + 如果您的游戏使用实例集，请使用实例集或别名 ID、会话名称和游戏的最大并发玩家数量调用 `CreateGameSession()`。
  + 如果您的游戏使用队列，请调用 `StartGameSessionPlacement()`。

 以下示例演示如何创建游戏会话。

```
public Amazon.GameLift.Model.GameSession()
{
    var cgsreq = new Amazon.GameLift.Model.CreateGameSessionRequest();
    //A unique identifier for the alias with the fleet to create a game session in.
    cgsreq.AliasId = aliasId; 
    //A unique identifier for a player or entity creating the game session 
    cgsreq.CreatorId = playerId; 
    //The maximum number of players that can be connected simultaneously to the game session.
    cgsreq.MaximumPlayerSessionCount = 4; 
						
    //Prompt an available server process to start a game session and retrieves connection information for the new game session
    Amazon.GameLift.Model.CreateGameSessionResponse cgsres = aglc.CreateGameSession(cgsreq);
    string gsid = cgsres.GameSession != null ? cgsres.GameSession.GameSessionId : "N/A";
    Debug.Log((int)cgsres.HttpStatusCode + " GAME SESSION CREATED: " + gsid);
    return cgsres.GameSession;
}
```

## 向游戏会话中添加玩家
<a name="integration-unity-client-sdk4-add-player"></a>

**注意**  
本主题指的是适用于 Unity 的 Amazon GameLift Servers 插件版本 1.0.0（使用服务器 SDK 4.x 或更早版本）。

在 Amazon GameLift Servers 创建了新游戏会话并返回 `GameSession` 后，便可以向其中添加玩家。

1. 通过新建玩家会话在游戏会话中预留玩家位置。将 `CreatePlayerSession` 或 `CreatePlayerSessions` 与游戏会话 ID 和每个玩家的唯一 ID 一起使用。

1. 连接到游戏会话。检索 `PlayerSession` 对象以获取游戏会话的连接信息。您可以使用此信息与服务器进程建立直接连接：

   1. 使用指定的端口以及分配给服务器进程的 DNS 名称或 IP 地址进行连接。

   1. 使用实例集的 DNS 名称和端口。如果实例集启用了 TLS 证书生成，则需要 DNS 名称和端口。

   1. 引用玩家会话 ID。如果游戏服务器验证传入的玩家连接，则需要玩家会话 ID。

以下示例演示了如何在游戏会话中预留玩家位置。

```
public Amazon.GameLift.Model.PlayerSession CreatePlayerSession(Amazon.GameLift.Model.GameSession gsession)
{
    var cpsreq = new Amazon.GameLift.Model.CreatePlayerSessionRequest();
    cpsreq.GameSessionId = gsession.GameSessionId; 
    //Specify game session ID.
    cpsreq.PlayerId = playerId; 
    //Specify player ID.
    Amazon.GameLift.Model.CreatePlayerSessionResponse cpsres = aglc.CreatePlayerSession(cpsreq);
    string psid = cpsres.PlayerSession != null ? cpsres.PlayerSession.PlayerSessionId : "N/A";
    return cpsres.PlayerSession;  
}
```

以下代码说明了如何将玩家连接到游戏会话。

```
public bool ConnectPlayer(int playerIdx, string playerSessionId)
{
    //Call ConnectPlayer with player ID and player session ID. 
    return server.ConnectPlayer(playerIdx, playerSessionId);
}
```

## 从游戏会中移除玩家
<a name="integration-unity-client-sdk4-remove-player"></a>

**注意**  
本主题指的是适用于 Unity 的 Amazon GameLift Servers 插件版本 1.0.0（使用服务器 SDK 4.x 或更早版本）。

当玩家离开游戏时，您可以将其从游戏会话中移除。

1. 通知 Amazon GameLift Servers 服务，有玩家已断开与服务器进程的连接。使用玩家的会话 ID 调用 `RemovePlayerSession`。

1. 验证 `RemovePlayerSession` 是否返回 `Success`。然后，Amazon GameLift Servers 将玩家位置更改为可用，Amazon GameLift Servers 可以将其分配给新玩家。

 以下示例说明了如何移除玩家会话。

```
public void DisconnectPlayer(int playerIdx)
{
    //Receive the player session ID. 
    string playerSessionId = playerSessions[playerIdx];
    var outcome = GameLiftServerAPI.RemovePlayerSession(playerSessionId);
    if (outcome.Success)
    {
        Debug.Log (":) PLAYER SESSION REMOVED");
    }
    else
    {
        Debug.Log(":(PLAYER SESSION REMOVE FAILED. RemovePlayerSession()
        returned " + outcome.Error.ToString());
    }
}
```