

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

# 整合適用於遊戲引擎的伺服器 SDK
<a name="integration-engines"></a>

您可以使用 受管Amazon GameLift Servers服務搭配大多數支援 C\$1\$1 或 C\$1 程式庫的主要遊戲引擎，包括 O3DE、Unreal Engine 和 Unity。建立您遊戲需要的版本；請參閱建立說明和最低需求的各版本 README 檔案。如需可用的 Amazon GameLift Servers 開發套件、支援的開發平台與作業系統等更多資訊，請參閱 [取得Amazon GameLift Servers開發工具](gamelift-supported.md) 的遊戲伺服器內容。

除本主題中提供的特定引擎資訊外，請參考下列主題以獲得有關在您的遊戲伺服器、用戶端和服務中整合 Amazon GameLift Servers 的更多說明：
+ [使用伺服器 SDK 將 Amazon GameLift Servers新增至您的遊戲伺服器](gamelift-sdk-server-api.md) – 在遊戲伺服器中整合 Amazon GameLift Servers 的詳細說明。
+ [整合Amazon GameLift Servers遊戲用戶端功能](gamelift-sdk-client-api.md) – 整合到遊戲用戶端或服務中的詳細說明，包括建立遊戲工作階段和將玩家加入遊戲。

## 虛擬引擎
<a name="integration-engines-unreal"></a>

**遊戲伺服器**  
將[Amazon GameLift Servers適用於 Unreal Engine 的伺服器 SDK](integration-server-sdk5-unreal-actions.md) 新增至您的專案，並實作所需的伺服器功能，Amazon GameLift Servers以準備在 上託管的遊戲伺服器。有關設定 Unreal Engine 外掛程式和加入 Amazon GameLift Servers 程式碼的協助，請參閱 [Amazon GameLift Servers 整合至 Unreal Engine 專案](integration-engines-setup-unreal.md)。

**遊戲用戶端與服務**  
啟用遊戲用戶端和/或遊戲服務與 Amazon GameLift Servers 服務進行互動，如查詢可用遊戲工作階段或建立新工作階段，以及將玩家加入遊戲。適用於 [AWS C\$1\$1 的 SDK](https://sdk.amazonaws.com/cpp/api/LATEST/namespace_aws_1_1_game_lift.html) 提供核心用戶端功能。若要將 Amazon GameLift Servers 整合到 Unreal Engine 遊戲專案中，請參閱 [整合Amazon GameLift Servers遊戲用戶端功能](gamelift-sdk-client-api.md)。

## Unity
<a name="integration-engines-unity"></a>

**遊戲伺服器**  
將[Amazon GameLift Servers適用於 C\$1 的伺服器 SDK](integration-server-sdk5-csharp-actions.md) 新增至您的專案，並實作必要的伺服器功能，Amazon GameLift Servers以準備在 上託管的遊戲伺服器。有關設定 Unity 和新增 Amazon GameLift Servers 程式碼的協助，請參閱 [Amazon GameLift Servers 整合至 Unity 專案](integration-engines-unity-using.md)。

**遊戲用戶端與服務**  
啟用遊戲用戶端和/或遊戲服務與 Amazon GameLift Servers 服務進行互動，如查詢可用遊戲工作階段或建立新工作階段，以及將玩家加入遊戲。核心用戶端功能在 [適用於 .NET 的 AWS SDK](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) 中提供。若要將 Amazon GameLift Servers 整合到 Unity 遊戲專案中，請參閱 [整合Amazon GameLift Servers遊戲用戶端功能](gamelift-sdk-client-api.md)。

## 其他引擎
<a name="integration-engines-other"></a>

有關遊戲伺服器和用戶端可使用的 Amazon GameLift Servers 開發套件的完整列表，請參閱 [取得Amazon GameLift Servers開發工具](gamelift-supported.md)。

# Amazon GameLift Servers 整合至 Unreal Engine 專案
<a name="integration-engines-setup-unreal"></a>

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

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

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

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

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

## 設定建置目標和模組規則
<a name="integration-engines-setup-unreal-setup"></a>

修改您的遊戲專案檔案，以正確產生建置元件，以搭配 使用Amazon GameLift Servers。

**若要新增用戶端和伺服器建置目標：**

1. 開啟遊戲專案的程式碼檔案，並找到 `.../Games/[your application name]Source/[your application name]Target.cs` 檔案。範例：`.../Source/GameLiftUnrealAppTarget.cs`。（如果您使用 Visual Studio，請開啟專案`.sln`的檔案。)

1. 複製此檔案以在 `Source/`目錄中建立新的兩個目標檔案。
   + 用戶端目標 – 將新檔案重新命名為 `[your application name]Client.Target.cs`。編輯內容以更新類別名稱和目標類型值，如下列範例程式碼所示：

     ```
     using UnrealBuildTool;
       using System.Collections.Generic;
     
       public class GameLiftUnrealAppClientTarget :  TargetRules
      {
          public GameLiftUnrealAppClientTarget ( TargetInfo Target ) :  base ( Target )
          {
              Type = TargetType.Client;
              DefaultBuildSettings = BuildSettingsVersion.V2;
              IncludeOrderVersion = EngineIncludeOrderVersion.Unreal5_1;
              ExtraModuleNames.Add( "GameLiftUnrealApp");
          }
      }
     ```
   + 伺服器目標 – 將新檔案重新命名為 `[your application name]Server.Target.cs`。編輯內容以更新類別名稱和目標類型值，如下列範例程式碼所示：

     ```
     using UnrealBuildTool;
       using System.Collections.Generic;
     
       public class GameLiftUnrealAppServerTarget :  TargetRules
      {
          public GameLiftUnrealAppServerTarget ( TargetInfo Target ) :  base ( Target )
          {
              Type = TargetType.Server;
              DefaultBuildSettings = BuildSettingsVersion.V2;
              IncludeOrderVersion = EngineIncludeOrderVersion.Unreal5_1;
              ExtraModuleNames.Add( "GameLiftUnrealApp");
          }
      }
     ```

1. 重新產生專案檔案。如果您使用的是 Visual Studio，您可以在遊戲專案的 `.uproject` 檔案上按一下滑鼠右鍵，然後選取**產生 Visual Studio 專案檔案**。

**若要更新遊戲專案模組規則：**

更新遊戲專案的模組規則，以依賴外掛程式。

1. 開啟遊戲專案的程式碼檔案，並找到 `.../Games/[your application name]Source/[your application name].Build.cs` 檔案。範例：`.../Source/GameLiftUnrealApp.Build.cs`。（如果您使用 Visual Studio，請開啟專案`.sln`的檔案。)

1. 找到 `ModuleRules`類別並更新，如下列範例程式碼所示：

   ```
   using UnrealBuildTool;
   
     public class GameLiftUnrealApp :  ModuleRules
    {
        public GameLiftUnrealApp ( ReadOnlyTargetRules Target ) :  base ( Target )
        {
            PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
            PublicDependencyModuleNames.AddRange( new string[] {  "Core",  "CoreUObject",  "Engine",  "InputCore",  "HeadMountedDisplay",  "EnhancedInput" });
         // Add the following section
            if (Target.Type == TargetType.Server)
            {
                PublicDependencyModuleNames.Add("GameLiftServerSDK");
            }
            else
            {
                PublicDefinitions.Add("WITH_GAMELIFT=0");
            }
            bEnableExceptions =  true;
        }
    }
   ```

1. 建立新的目標檔案並修改模組規則後，請重建您的遊戲專案。

## 將遊戲託管功能新增至您的伺服器程式碼
<a name="integration-engines-setup-unreal-code"></a>

在安裝和設定伺服器 SDK 之後，下一步是將遊戲託管功能整合到您的伺服器程式碼。伺服器開發套件可讓您的遊戲伺服器與 Amazon GameLift Servers服務通訊、接收遊戲工作階段的指示、報告狀態和運作狀態，以及執行其他動作。

本主題提供範例程式碼，新增使用 託管遊戲所需的最低功能Amazon GameLift Servers。

**步驟 1：更新`GameMode`標頭檔案**

1. 開啟遊戲專案的程式碼檔案，並找到 `Your-application-nameGameMode.h` 檔案。範例：`GameLiftUnrealAppGameMode.h`。如果您使用 Visual Studio，請開啟遊戲專案`.sln`的檔案。

1. 變更標頭檔案以包含下列範例程式碼。請務必將 "GameLiftUnrealApp" 取代為您自己的應用程式名稱。

### GameMode.h 的範例程式碼
<a name="w2aab9c11c11b9c17c15b9b1"></a>

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "GameLiftUnrealAppGameMode.generated.h"

struct FProcessParameters;

DECLARE_LOG_CATEGORY_EXTERN(GameServerLog, Log, All);

UCLASS(minimalapi)
class AGameLiftUnrealAppGameMode : public AGameModeBase
{
    GENERATED_BODY()

public:
    AGameLiftUnrealAppGameMode();

protected:
    virtual void BeginPlay() override;

private:
    void InitGameLift();

private:
    TSharedPtr<FProcessParameters> ProcessParameters;
};
```

**步驟 2：將必要的伺服器 SDK 呼叫新增至遊戲伺服器程式碼**

使用本節中的範例程式碼來整合遊戲伺服器程式碼，以便與 搭配使用Amazon GameLift Servers。如需程式碼功能的詳細資訊，請參閱 [初始化伺服器程序](gamelift-sdk-server-api.md#gamelift-sdk-server-initialize)和 [適用於 -- 動作的 C\$1\$1 (Unreal) 伺服器 SDK Amazon GameLift Servers 5.x](integration-server-sdk5-unreal-actions.md)。
**注意**  
`WITH_GAMELIFT` 預處理器旗標有兩個用途：  
僅限制對 Unreal 伺服器建置的Amazon GameLift Servers後端 API 呼叫
確保不同 Unreal 建置目標的相容性

1. 開啟相關的來源`Your-application-nameGameMode.cpp`檔案。在我們的範例中：`GameLiftUnrealAppGameMode.cpp`。

1. 變更程式碼以符合下列範例程式碼。請務必將 "GameLiftUnrealApp" 的任何執行個體取代為您自己的應用程式名稱。

   提供的程式碼範例示範如何新增與 整合所需的元素Amazon GameLift Servers。其中包含：
   + 初始化 Amazon GameLift Servers API 用戶端。
   + 實作回呼函數以回應來自 Amazon GameLift Servers服務的請求，包括 `OnStartGameSession`、 `OnProcessTerminate`和 `onHealthCheck`。
   + 準備好託管遊戲工作階段時，請呼叫 `ProcessReady()` 通知Amazon GameLift Servers服務。

### GameMode.cpp 的範例程式碼
<a name="w2aab9c11c11b9c17c15c13b1"></a>

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

#include "GameLiftUnrealAppGameMode.h"

#include "UObject/ConstructorHelpers.h"
#include "Kismet/GameplayStatics.h"

#if WITH_GAMELIFT
#include "GameLiftServerSDK.h"
#include "GameLiftServerSDKModels.h"
#endif

#include "GenericPlatform/GenericPlatformOutputDevices.h"

DEFINE_LOG_CATEGORY(GameServerLog);

AGameLiftUnrealAppGameMode::AGameLiftUnrealAppGameMode() :
    ProcessParameters(nullptr)
{
    // Set default pawn class to our Blueprinted character
    static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPerson/Blueprints/BP_ThirdPersonCharacter"));

    if (PlayerPawnBPClass.Class != NULL)
    {
        DefaultPawnClass = PlayerPawnBPClass.Class;
    }

    UE_LOG(GameServerLog, Log, TEXT("Initializing AGameLiftUnrealAppGameMode..."));
}

void AGameLiftUnrealAppGameMode::BeginPlay()
{
    Super::BeginPlay();

#if WITH_GAMELIFT
    InitGameLift();
#endif
}

void AGameLiftUnrealAppGameMode::InitGameLift()
{
#if WITH_GAMELIFT
    UE_LOG(GameServerLog, Log, TEXT("Calling InitGameLift..."));

    // Getting the module first.
    FGameLiftServerSDKModule* GameLiftSdkModule = &FModuleManager::LoadModuleChecked<FGameLiftServerSDKModule>(FName("GameLiftServerSDK"));

    //Define the server parameters for a GameLift Anywhere fleet. These are not needed for a GameLift managed EC2 fleet.
    FServerParameters ServerParametersForAnywhere;

    bool bIsAnywhereActive = false;
    if (FParse::Param(FCommandLine::Get(), TEXT("glAnywhere")))
    {
        bIsAnywhereActive = true;
    }

    if (bIsAnywhereActive)
    {
        UE_LOG(GameServerLog, Log, TEXT("Configuring server parameters for Anywhere..."));

        // If GameLift Anywhere is enabled, parse command line arguments and pass them in the ServerParameters object.
        FString glAnywhereWebSocketUrl = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereWebSocketUrl="), glAnywhereWebSocketUrl))
        {
            ServerParametersForAnywhere.m_webSocketUrl = TCHAR_TO_UTF8(*glAnywhereWebSocketUrl);
        }

        FString glAnywhereFleetId = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereFleetId="), glAnywhereFleetId))
        {
            ServerParametersForAnywhere.m_fleetId = TCHAR_TO_UTF8(*glAnywhereFleetId);
        }

        FString glAnywhereProcessId = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereProcessId="), glAnywhereProcessId))
        {
            ServerParametersForAnywhere.m_processId = TCHAR_TO_UTF8(*glAnywhereProcessId);
        }
        else
        {
            // If no ProcessId is passed as a command line argument, generate a randomized unique string.
            FString TimeString = FString::FromInt(std::time(nullptr));
            FString ProcessId = "ProcessId_" + TimeString;
            ServerParametersForAnywhere.m_processId = TCHAR_TO_UTF8(*ProcessId);
        }

        FString glAnywhereHostId = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereHostId="), glAnywhereHostId))
        {
            ServerParametersForAnywhere.m_hostId = TCHAR_TO_UTF8(*glAnywhereHostId);
        }

        FString glAnywhereAuthToken = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereAuthToken="), glAnywhereAuthToken))
        {
            ServerParametersForAnywhere.m_authToken = TCHAR_TO_UTF8(*glAnywhereAuthToken);
        }

        FString glAnywhereAwsRegion = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereAwsRegion="), glAnywhereAwsRegion))
        {
            ServerParametersForAnywhere.m_awsRegion = TCHAR_TO_UTF8(*glAnywhereAwsRegion);
        }

        FString glAnywhereAccessKey = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereAccessKey="), glAnywhereAccessKey))
        {
            ServerParametersForAnywhere.m_accessKey = TCHAR_TO_UTF8(*glAnywhereAccessKey);
        }

        FString glAnywhereSecretKey = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereSecretKey="), glAnywhereSecretKey))
        {
            ServerParametersForAnywhere.m_secretKey = TCHAR_TO_UTF8(*glAnywhereSecretKey);
        }

        FString glAnywhereSessionToken = "";
        if (FParse::Value(FCommandLine::Get(), TEXT("glAnywhereSessionToken="), glAnywhereSessionToken))
        {
            ServerParametersForAnywhere.m_sessionToken = TCHAR_TO_UTF8(*glAnywhereSessionToken);
        }

        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_YELLOW);
        UE_LOG(GameServerLog, Log, TEXT(">>>> WebSocket URL: %s"), *ServerParametersForAnywhere.m_webSocketUrl);
        UE_LOG(GameServerLog, Log, TEXT(">>>> Fleet ID: %s"), *ServerParametersForAnywhere.m_fleetId);
        UE_LOG(GameServerLog, Log, TEXT(">>>> Process ID: %s"), *ServerParametersForAnywhere.m_processId);
        UE_LOG(GameServerLog, Log, TEXT(">>>> Host ID (Compute Name): %s"), *ServerParametersForAnywhere.m_hostId);
        UE_LOG(GameServerLog, Log, TEXT(">>>> Auth Token: %s"), *ServerParametersForAnywhere.m_authToken);
        UE_LOG(GameServerLog, Log, TEXT(">>>> Aws Region: %s"), *ServerParametersForAnywhere.m_awsRegion);
        UE_LOG(GameServerLog, Log, TEXT(">>>> Access Key: %s"), *ServerParametersForAnywhere.m_accessKey);
        UE_LOG(GameServerLog, Log, TEXT(">>>> Secret Key: %s"), *ServerParametersForAnywhere.m_secretKey);
        UE_LOG(GameServerLog, Log, TEXT(">>>> Session Token: %s"), *ServerParametersForAnywhere.m_sessionToken);
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_NONE);
    }

    UE_LOG(GameServerLog, Log, TEXT("Initializing the GameLift Server..."));

    //InitSDK will establish a local connection with GameLift's agent to enable further communication.
    FGameLiftGenericOutcome InitSdkOutcome = GameLiftSdkModule->InitSDK(ServerParametersForAnywhere);
    if (InitSdkOutcome.IsSuccess())
    {
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_GREEN);
        UE_LOG(GameServerLog, Log, TEXT("GameLift InitSDK succeeded!"));
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_NONE);
    }
    else
    {
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_RED);
        UE_LOG(GameServerLog, Log, TEXT("ERROR: InitSDK failed : ("));
        FGameLiftError GameLiftError = InitSdkOutcome.GetError();
        UE_LOG(GameServerLog, Log, TEXT("ERROR: %s"), *GameLiftError.m_errorMessage);
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_NONE);
        return;
    }

    ProcessParameters = MakeShared<FProcessParameters>();

    //When a game session is created, Amazon GameLift Servers sends an activation request to the game server and passes along the game session object containing game properties and other settings.
    //Here is where a game server should take action based on the game session object.
    //Once the game server is ready to receive incoming player connections, it should invoke GameLiftServerAPI.ActivateGameSession()
    ProcessParameters->OnStartGameSession.BindLambda([=](Aws::GameLift::Server::Model::GameSession InGameSession)
        {
            FString GameSessionId = FString(InGameSession.GetGameSessionId());
            UE_LOG(GameServerLog, Log, TEXT("GameSession Initializing: %s"), *GameSessionId);
            GameLiftSdkModule->ActivateGameSession();
        });

    //OnProcessTerminate callback. Amazon GameLift Servers will invoke this callback before shutting down an instance hosting this game server.
    //It gives this game server a chance to save its state, communicate with services, etc., before being shut down.
    //In this case, we simply tell Amazon GameLift Servers we are indeed going to shut down.
    ProcessParameters->OnTerminate.BindLambda([=]()
        {
            UE_LOG(GameServerLog, Log, TEXT("Game Server Process is terminating"));
            // First call ProcessEnding()
            FGameLiftGenericOutcome processEndingOutcome = GameLiftSdkModule->ProcessEnding();
            // Then call Destroy() to free the SDK from memory
            FGameLiftGenericOutcome destroyOutcome = GameLiftSdkModule->Destroy();
            // Exit the process with success or failure
            if (processEndingOutcome.IsSuccess() && destroyOutcome.IsSuccess()) {
                UE_LOG(GameServerLog, Log, TEXT("Server process ending successfully"));
            }
            else {
                if (!processEndingOutcome.IsSuccess()) {
                    const FGameLiftError& error = processEndingOutcome.GetError();
                    UE_LOG(GameServerLog, Error, TEXT("ProcessEnding() failed. Error: %s"),
                    error.m_errorMessage.IsEmpty() ? TEXT("Unknown error") : *error.m_errorMessage);
                }
                if (!destroyOutcome.IsSuccess()) {
                    const FGameLiftError& error = destroyOutcome.GetError();
                    UE_LOG(GameServerLog, Error, TEXT("Destroy() failed. Error: %s"),
                    error.m_errorMessage.IsEmpty() ? TEXT("Unknown error") : *error.m_errorMessage);
                }
            }
        });
         
    //This is the HealthCheck callback.
    //Amazon GameLift Servers will invoke this callback every 60 seconds or so.
    //Here, a game server might want to check the health of dependencies and such.
    //Simply return true if healthy, false otherwise.
    //The game server has 60 seconds to respond with its health status. Amazon GameLift Servers will default to 'false' if the game server doesn't respond in time.
    //In this case, we're always healthy!
    ProcessParameters->OnHealthCheck.BindLambda([]()
        {
            UE_LOG(GameServerLog, Log, TEXT("Performing Health Check"));
            return true;
        });

    //GameServer.exe -port=7777 LOG=server.mylog
    ProcessParameters->port = FURL::UrlConfig.DefaultPort;
    TArray<FString> CommandLineTokens;
    TArray<FString> CommandLineSwitches;

    FCommandLine::Parse(FCommandLine::Get(), CommandLineTokens, CommandLineSwitches);

    for (FString SwitchStr : CommandLineSwitches)
    {
        FString Key;
        FString Value;

        if (SwitchStr.Split("=", &Key, &Value))
        {
            if (Key.Equals("port"))
            {
                ProcessParameters->port = FCString::Atoi(*Value);
            }
        }
    }

    //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.
    TArray<FString> Logfiles;
    Logfiles.Add(TEXT("GameLiftUnrealApp/Saved/Logs/server.log"));
    ProcessParameters->logParameters = Logfiles;

    //The game server calls ProcessReady() to tell Amazon GameLift Servers it's ready to host game sessions.
    UE_LOG(GameServerLog, Log, TEXT("Calling Process Ready..."));
    FGameLiftGenericOutcome ProcessReadyOutcome = GameLiftSdkModule->ProcessReady(*ProcessParameters);

    if (ProcessReadyOutcome.IsSuccess())
    {
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_GREEN);
        UE_LOG(GameServerLog, Log, TEXT("Process Ready!"));
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_NONE);
    }
    else
    {
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_RED);
        UE_LOG(GameServerLog, Log, TEXT("ERROR: Process Ready Failed!"));
        FGameLiftError ProcessReadyError = ProcessReadyOutcome.GetError();
        UE_LOG(GameServerLog, Log, TEXT("ERROR: %s"), *ProcessReadyError.m_errorMessage);
        UE_LOG(GameServerLog, SetColor, TEXT("%s"), COLOR_NONE);
    }

    UE_LOG(GameServerLog, Log, TEXT("InitGameLift completed!"));
#endif
}
```

**步驟 3：重建遊戲專案**
+ 為下列兩種目標類型建置遊戲專案：*Development Editor* 和 *Development Server*。
**注意**  
您不需要重建解決方案。反之，請在應用程式的 `/Games/` 資料夾下建置專案。否則，Visual Studio 會重建整個 UE5 專案，最多可能需要一小時。

## 封裝遊戲伺服器以進行託管
<a name="integration-engines-setup-unreal-package"></a>

您的遊戲伺服器程式碼現在已與最基本的伺服器 SDK 功能整合，您已準備好使用 Unreal Editor 封裝遊戲伺服器組建。

**封裝遊戲伺服器組建**

1. 在 Unreal Editor 中開啟遊戲專案。

1. 遵循 Unreal Editor 步驟來封裝遊戲伺服器：
   + 選擇您的目標平台 (Windows 或 Linux)。
   + 選取您的伺服器建置目標 (`[your application name]Server`。

   封裝程序會產生您的遊戲伺服器可執行檔：`[your application name]Server.exe`。

1. 準備您的遊戲伺服器建置，以便部署以託管資源。組建應包含下列檔案：
   + 您的遊戲伺服器可執行檔
   + 如果您使用的是 Unreal Engine 5.5 版或更新版本，請針對 Windows 組建包含下列檔案。您可以在 Unreal Engine 的來源建置版本中找到它們：
     + `VC_redist.x64.exe` (`UnrealEngine\Engine\Source\Programs\PrereqInstaller\Resources\VCRedist\`)
     + `UEPrereqSetup_x64.exe or UE5PrereqSetup_x64.exe` (`UnrealEngine\Engine\Extras\Redist\en-us\`)
   + 遊戲伺服器的所有其他必要相依性。
   + 如有需要，OpenSSL 程式庫。如果您的遊戲伺服器已與Amazon GameLift Servers伺服器 SDK 5.3 版或更新版本整合，您可以略過此步驟。[您可以在此處取得最新的伺服器 SDK 版本。](https://github.com/amazon-gamelift/amazon-gamelift-plugin-unreal)

### 使用適用於 Unreal 的伺服器 SDK 5.2 版及更早版本建立的遊戲伺服器所需的 OpenSSL 程式庫
<a name="w2aab9c11c11b9c17c25b7b1"></a>

您必須包含與在 Unreal 中封裝遊戲伺服器時所使用的相同 OpenSSL 程式庫版本。這些程式庫位於您的遊戲引擎來源中。位置會根據您的開發環境而有所不同：

在 Windows 上：
+ `[ENGINE_ROOT_DIR]\Engine\Extras\ThirdPartyNotUE\libimobiledevice\x64\libssl-1_1-x64.dll`
+ `[ENGINE_ROOT_DIR]\Engine\Extras\ThirdPartyNotUE\libimobiledevice\x64\libcrypto-1_1-x64.dll` 

在 Linux 上：
+ `Engine/Source/Thirdparty/OpenSSL/1.1.1n/include/libssl.so.1.1`
+ `Engine/Source/Thirdparty/OpenSSL/1.1.1n/include/libcrypto.so.1.1`

將 OpenSSL 程式庫複製到與遊戲伺服器可執行檔位於相同目錄中的遊戲組建套件。

## 後續步驟
<a name="integration-engines-setup-unreal-next"></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\$1\$1 (Unreal) 伺服器 SDK Amazon GameLift Servers 5.x](integration-server-sdk5-unreal-actions.md)
+ 自訂您的遊戲用戶端元件以請求遊戲工作階段、接收連線資訊，並直接連線至遊戲伺服器以玩遊戲。如需指引，請參閱這些主題：
  + [整合Amazon GameLift Servers遊戲用戶端功能](gamelift-sdk-client-api.md)

# 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\$1 伺服器 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\$1 伺服器 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\$1 伺服器 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\$1\$1 (Unreal) 伺服器 SDK Amazon GameLift Servers 5.x](integration-server-sdk5-unreal-actions.md)
+ 自訂您的遊戲用戶端元件以請求遊戲工作階段、接收連線資訊，並直接連線至遊戲伺服器以玩遊戲。如需指引，請參閱這些主題：
  + [整合Amazon GameLift Servers遊戲用戶端功能](gamelift-sdk-client-api.md)