

# Prepare your Unreal or Unity game with the Amazon GameLift Servers plugin
Prepare with the game engine plugin

The Amazon GameLift Servers plugin is a full-featured add-on to your Unreal or Unity game engine. It guides you through the basic steps to deploy your game for hosting with Amazon GameLift Servers. With the plugin's tool set and workflows, you can work in your game engine development environment to prepare your game server for hosting, set up hosting on a local machine for testing, create a simple backend service, and deploy your game server to managed cloud-based hosting. 

Use the plugin to experience working with Amazon GameLift Servers and get a game hosting solution up and running fast. You can work with sample game assets or your own game project. The plugin automates a number of steps so that you can quickly build a simple working solution. When you complete the plugin's guided workflows, you'll be able to connect a game client to live hosted game sessions through Amazon GameLift Servers. After using the plugin to create a simple hosting solution, you can customize your solution to meet the needs of your game.

The plugin is available for the following game engines:
+ Unreal Engine
+ Unity

The plugin includes these components for each game engine: 
+ Plugin modules for the game engine editor. When the plugin is installed, a new main menu button gives you access to Amazon GameLift Servers functionality.
+ Libraries for the Amazon GameLift Servers service API with client-side functionality. 
+ Libraries for the Amazon GameLift Servers server SDK (version 5).
+ Sample assets for use with testing a server integration.
+ Editable configurations, in the form of CloudFormation templates, that define your game server solution.

**Topics**
+ [

## Plugin workflow
](#getting-started-plugin-workflow)
+ [

# Amazon GameLift Servers plugin for Unreal Engine
](unreal-plugin.md)
+ [

# Amazon GameLift Servers plugin for Unity (server SDK 5.x)
](unity-plug-in.md)
+ [

# Amazon GameLift Servers plugin for Unity for server SDK 4
](unity-plug-in-sdk4.md)

## Plugin workflow


The following steps describe a typical path to preparing and deploying your game project on Amazon GameLift Servers. You complete these steps by working in the game engine editor and your game code. 

1. Create a user profile that links to your AWS account user and provides access credentials with permissions to use Amazon GameLift Servers.

1. Set up related AWS resources that the plugin uses in the hosting solution (referred to as "bootstrapping"). 

1. Add server code to your project to establish communication between a running game server and the Amazon GameLift Servers service.

1. Add client code to your project that lets game clients send requests to Amazon GameLift Servers to start new game sessions and then connect to them.

1. Use the Anywhere workflow to set up your local workstation as an Anywhere compute and host your game server. Launch your game server and client locally through the plugin, connect to a game session, and test the integration.

1. Use the Managed EC2 workflow to upload your game server to Amazon GameLift Servers and deploy a simple but complete cloud hosting solution. Launch your game client locally through the plugin, request a game session and connect to it, and play your game.

When working in the plugin, you'll create and use AWS resources, These actions might incur charges to the AWS account in use. If you're new to AWS, these actions might be covered under the [AWS Free Tier](https://aws.amazon.com/free/).

# Amazon GameLift Servers plugin for Unreal Engine
Plugin for Unreal Engine

This plugin adds the Amazon GameLift Servers C\$1\$1 server SDK and tools to the UE editor. Use the guided UI workflows to integrate server SDK functionality into your game project and deploy an Amazon GameLift Servers hosting solution for your game server. 

With the plugin, you can build a basic working hosting solution and then optimize and customize as needed. Set up an Amazon GameLift Servers Anywhere fleet with your local workstation as a host. For cloud hosting with managed EC2 or managed container fleets, deploy your game server with a complete solution to manage game session requests and client connections.

**Topics**
+ [

## Install the plugin for your Unreal game project
](#unreal-plugin-install)
+ [

## Next steps: Customize your game hosting solution
](#unreal-plugin-next-steps)
+ [

# Plugin for Unreal: Set up an AWS user profile
](unreal-plugin-profiles.md)
+ [

# Plugin for Unreal: Integrate your game code
](unreal-plugin-integrate.md)
+ [

# Plugin for Unreal: Host your game locally with Amazon GameLift Servers Anywhere
](unreal-plugin-anywhere.md)
+ [

# Plugin for Unreal: Deploy your game to a managed EC2 fleet
](unreal-plugin-ec2.md)
+ [

# Plugin for Unreal: Deploy your game to a managed container fleet
](unreal-plugin-container.md)

## Install the plugin for your Unreal game project
Install the plugin

**[ Get the Amazon GameLift Servers plugin for Unreal Engine from GitHub](https://github.com/amazon-gamelift/amazon-gamelift-plugin-unreal)**

See the GitHub repository readme for information about how to install the plugin in your Unreal Editor for a game project. 

The plugin includes these components: 
+ Plugin modules for the UE editor. When the plugin is installed, a new main menu button gives you access to Amazon GameLift Servers functionality.
+ C\$1\$1 libraries for the Amazon GameLift Servers service API. Use API functionality in a client-side backend service to help game clients request game sessions and send/retrieve game session information. 
+ Unreal libraries for the Amazon GameLift Servers server SDK (version 5). Use the server SDK in your game server code to manage communication between hosted game server processes and the Amazon GameLift Servers service.
+ Content for testing, including a startup game map and two testing maps with basic blueprints and UI elements for use with testing a server integration.
+ Editable configurations, in the form of CloudFormation templates, that the plugin uses when deploying your game server for hosting.

This plugin uses AWS CloudFormation templates to deploy hosting solutions for common gaming scenarios. Use these solutions as provided or customize them as needed for your games.

## Next steps: Customize your game hosting solution
Customize your game hosting solution

Using the plugin's guided workflows is a good way to get up and running fast with an Amazon GameLift Servers hosting solution. With the plugin, you can set up basic versions of each of your solution's components.

When you're ready, you can build on this basic solution by customizing each component, and fine-tuning your solution as you prepare for game launch. Consider these options: 
+ Modify your fleets and fleet configurations. See [Hosting resource customizations](fleets-design.md).
+ Customize your game session queue configuration. See [Customize a game session queue](queues-design.md): 
+ Add functionality to your game server and game client. See [Integrate a game server with Amazon GameLift Servers](gamelift-sdk-server.md) and [Integrate Amazon GameLift Servers game client functionality](gamelift-sdk-client-api.md).
+ Customize your backend service. See [Build a backend service for Amazon GameLift Servers](gamelift_quickstart_customservers_designbackend.md).
+ Set up automatic capacity scaling to meet expected player demand. See [Scaling game hosting capacity with Amazon GameLift Servers](fleets-manage-capacity.md).
+ Set up hosting observability tools, including analytics and logging. See [Monitoring Amazon GameLift Servers](monitoring-overview.md).
+ Automate your deployment using [infrastructure as code (IaC)](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html). The plugin's guided workflows for managed solutions use AWS CloudFormation templates. You can customize these as needed. See [Manage Amazon GameLift Servers hosting resources using CloudFormation](resources-cloudformation.md).

**Topics**
+ [

## Install the plugin for your Unreal game project
](#unreal-plugin-install)
+ [

## Next steps: Customize your game hosting solution
](#unreal-plugin-next-steps)
+ [

# Plugin for Unreal: Set up an AWS user profile
](unreal-plugin-profiles.md)
+ [

# Plugin for Unreal: Integrate your game code
](unreal-plugin-integrate.md)
+ [

# Plugin for Unreal: Host your game locally with Amazon GameLift Servers Anywhere
](unreal-plugin-anywhere.md)
+ [

# Plugin for Unreal: Deploy your game to a managed EC2 fleet
](unreal-plugin-ec2.md)
+ [

# Plugin for Unreal: Deploy your game to a managed container fleet
](unreal-plugin-container.md)

# Plugin for Unreal: Set up an AWS user profile
Set up an AWS user profile

After installing the plugin, set up a user profile with a valid AWS account. You can maintain multiple profiles in the plugin, but you can have only one profile selected at a time. Whenever you work in the plugin, select a profile to use. Each workflow page displays the currently selected profile. 

Maintaining multiple profiles gives you the ability to switch between different hosting deployments. For example, you might set up profiles that use the same AWS account but deploy to different AWS Regions. Or you might set up profiles with different AWS accounts or users and permission sets.

**Note**  
If you've installed the AWS CLI on your workstation and have a profile already configured, the Amazon GameLift Servers plugin will detect it and list it as an existing profile. The plugin automatically selects any profile named `[default]`. You can use an existing profile or create a new one. 

All profiles must be bootstrapped to set up some required AWS resources under your account user.

**To manage your AWS profiles**

1. In the Unreal editor main toolbar, choose the Amazon GameLift Servers menu, and select **AWS Access Credentials**. This action opens the Amazon GameLift Servers plugin to the page **Set up your user profile**.

1. Use the buttons to create a new AWS account or set up a user profile for an AWS account that you already have. 

1. If you don't already have a user profile, you're prompted to enter profile details and create a new profile. Provide the following information:
   + An AWS account. If you create a new AWS account, use the link to the AWS Management Console and follow the prompts. See [ Create an AWS account](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html) for more details.
   + An AWS user with permissions to use Amazon GameLift Servers and other required AWS services. See [Set up an AWS user account](setting-up-aws-login.md) for instructions on setting up an AWS Identity and Access Management (IAM) user with Amazon GameLift Servers permissions and programmatic access with long-term credentials.
   + Credentials for your AWS user. These credentials consist of an AWS access key ID and AWS secret key. See [ Get your access keys](https://docs.aws.amazon.com/cli/latest/userguide/cli-authentication-user.html#cli-authentication-user-get) for more details.
   + AWS region. This is a geographic location where you want to create your AWS resources for hosting. During development, we recommend using a region close to your physical location. Choose a region from the list of [ supported AWS regions](https://docs.aws.amazon.com/general/latest/gr/gamelift.html).

1. If the plugin detects existing profiles, it displays a list of available profiles. Select an existing profile from the list, or choose **Add another profile** to create a new one. 

## Bootstrap a user profile


All profiles must be bootstrapped to use with the Amazon GameLift Servers plugin. Bootstrapping creates an Amazon S3 bucket specific to the profile. It's used to store project configurations, build artifacts, and other dependencies. Buckets are not shared between other profiles.

Bootstrapping involves creating new AWS resources and might incur costs.

**To bootstrap your profile:**

1. On the **AWS Access Credentials** page, check the bootstrap status of the user profile that you want to use. If the profile's bootstrap status is "Inactive" and there's no S3 bucket listed, you need to bootstrap the profile. 

1. Select the profile you want to use and choose **Bootstrap profile**. 

1. Wait for bootstrap status to change to "Active". This can take a few minutes.

# Plugin for Unreal: Integrate your game code
Integrate your game code

Before you can deploy your game server to a fleet, you need to make a series of updates to game code and package game components for use with the Amazon GameLift Servers service.

This topic walks through the steps for doing a minimal integration. For server integration, use the provided code sample to update your project's game mode. 
+ [Set up build targets and module rules](#unreal-plugin-anywhere-integrate-setup)
+ [Update your game server code](#unreal-plugin-anywhere-integrate-simple-server)
+ [Integrate your client game map](#unreal-plugin-anywhere-integrate-simple-client)
+ [Package your game components](#unreal-plugin-anywhere-integrate-build)

## Set up build targets and module rules


Modify your game project files to properly generate build components for use with Amazon GameLift Servers.

**To add client and server build targets:**

1. Open your game project's code files and locate the file `.../Games/[your application name]Source/[your application name]Target.cs` file. Example: `.../Source/GameLiftUnrealAppTarget.cs`. (If you use Visual Studio, open the project's `.sln` file.)

1. Copy this file to create two new target files in the `Source/` directory. 
   + Client target – Rename the new file to `[your application name]Client.Target.cs`. Edit the contents to update the class name and target type values, as illustrated in the following sample code: 

     ```
     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");
          }
      }
     ```
   + Server target – Rename the new file to `[your application name]Server.Target.cs`. Edit the contents to update the class name and target type values, as illustrated in the following sample code: 

     ```
     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. Regenerate your project files. If you're using Visual Studio, you can right-click your game project's `.uproject` file and select **Generate Visual Studio Project Files**.

**To update the game project module rules:**

Update the game project's module rules to take a dependency on the plugin.

1. Open your game project's code files and locate the file `.../Games/[your application name]Source/[your application name].Build.cs` file. Example: `.../Source/GameLiftUnrealApp.Build.cs`. (If you use Visual Studio, open the project's `.sln` file.)

1. Locate the `ModuleRules` class and update as illustrated in the following sample code: 

   ```
   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. After creating the new target files and modifying the module rules, rebuild your game project.

## Update your game server code


Update your game server code to enable communication between a game server process and the Amazon GameLift Servers service. Your game server must be able to respond to requests from Amazon GameLift Servers, such as to start and stop new game sessions.

**To add server code for Amazon GameLift Servers**

1. In your code editor, open the solution (`.sln`) file for your game project, usually found in the project root folder. For example: `GameLiftUnrealApp.sln`.

1. With the solution open, locate the project game mode header file: `[project-name]GameMode.h` file. For example: `GameLiftUnrealAppGameMode.h`. 

1. Change the header file to align with the following code. Be sure to replace "GameLiftServer" with your own project name. These updates are specific to the game server; we recommend that you make a backup copy of the original game mode files for use with your client.

### Example gameMode.h code


```
// 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;
};
```
+ Open the related source file `[project-name]GameMode.cpp` file (for example `GameLiftUnrealAppGameMode.cpp`). Change the code to align with the following example code. Be sure to replace "GameLiftUnrealApp" with your own project name. These updates are specific to the game server; we recommend that you make a backup copy of the original file for use with your client.

  The following example code shows how to add the minimum required elements for server integration with Amazon GameLift Servers:
  + Initialize an Amazon GameLift Servers API client. The `InitSDK()` call with server parameters is required for an Amazon GameLift Servers Anywhere fleet. When you connect to an Anywhere fleet, the plugin stores the server parameters as console arguments The sample code can access the values at runtime. 
  + Implement required callback functions to respond to requests from the Amazon GameLift Servers service, including `OnStartGameSession`, `OnProcessTerminate`, and `onHealthCheck`.
  + Call `ProcessReady()` with a designated port to notify the Amazon GameLift Servers service when ready to host game sessions.

### Example game server code


```
// 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 shutdown.
    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
}
```

## Integrate your client game map


The startup game map contains blueprint logic and UI elements that already include basic code to request game sessions and use connection information to connect to a game session. You can use the map as is or modify these as needed. Use the startup game map with other game assets, such as the Third Person template project provided by Unreal Engine. These assets are available in Content Browser. You can use them to test the plugin's deployment workflows, or as a guide to create a custom backend service for your game.

The startup map has the following characteristics: 
+ It includes logic for both an Anywhere fleet and a managed EC2 fleet. When you run your client, you can choose to connect to either fleet.
+ Client functionality includes find a game session (`SearchGameSessions()`), create a new game session (`CreateGameSession()`), and join a game session directly.
+ It gets a unique player ID from your project's Amazon Cognito user pool (this is part of a deployed Anywhere solution). 

**To use the startup game map**

1. In the UE editor, open the **Project Settings, Maps & Modes** page, and expand the **Default Maps** section.

1. For **Editor Startup Map**, select "StartupMap" from the dropdown list. You might need to search for the file, which is located in `... > Unreal Projects/[project-name]/Plugins/Amazon GameLift Servers Plugin Content/Maps`.

1. For **Game Default Map**, select the same "StartupMap" from the dropdown list.

1. For **Server Default Map**, select "Lv1\$1ThirdPerson" for Unreal Engine 5.6 or later, or "ThirdPersonMap" for earlier versions. This is a default map included in your game project. This map is designed for two players in the game.

1. Open the details panel for the server default map. Set **GameMode Override** to "None".

1. Expand the **Default Modes** section, and set **Global Default Server Game Mode** to the game mode you updated for your server integration. 

After you've made these changes to your project, you're ready to build your game components.

**Note**  
For Unreal Engine 5.6 or later, if you cannot move the character after connecting to the game server, update the BP\$1ThirdPersonCharacter blueprint to add input mapping context for `IMC_Default` and `IMC_MouseLook` as shown below:  

![\[alt text not found\]](http://docs.aws.amazon.com/gameliftservers/latest/developerguide/images/unreal-enhanced-input-blueprint.png)


## Package your game components


**To package your game server and game client builds**

1. Open your game project in a source-built version of the Unreal Engine editor.

1. If using Unreal Engine 5.6 or later, go to **Edit, Project Settings, Packaging**. Find **Cook everything in the project content directory** and enable it.

1. Use the editor to package your game client and server builds. 

   1. Choose a target. Go to **Platforms, Windows** and select one of the following:
      + Server: `[your-application-name]Server`
      + Client: `[your-application-name]Client`

   1. Start the build. Go to **Platform, Windows, Package Project**.

Each packaging process generates an executable: `[your-application-name]Client.exe` or `[your-application-name]Server.exe`.

In the plugin, set the paths to the client and server build executables on your local workstation.

# Plugin for Unreal: Host your game locally with Amazon GameLift Servers Anywhere
Host your game locally with Anywhere

Use this workflow to set up your local workstation as a game server host using an Anywhere fleet. You can use it to test your game server integration before deploying to a cloud-based managed fleet. It can also be useful for local testing during iterative game development.

**To start the Amazon GameLift Servers Anywhere workflow:**
+ In the Unreal editor main toolbar, choose the Amazon GameLift Servers menu, and select **Host with Anywhere**. This action opens the plugin page **Deploy Anywhere**, which presents a six-step process to integrate, build, and launch your game components. 

## Step 1: Set your profile


Choose the profile you want to use when following this workflow. The profile you select impacts all steps in the workflow. All resources you create are associated with the profile's AWS account and are placed in the profile's default AWS Region. The profile user's permissions determine your access to AWS resources and actions.

**To set a user profile**

1. Select a profile from the dropdown list of available profiles. If you don't have a profile yet or want to create a new one, go to the **Amazon GameLift** menu and choose **Set AWS User Profiles**.

1. If bootstrap status is not "Active", choose **Bootstrap profile** and wait for the status to change to "Active".

## Step 2: Set up your game code


In this step, prepare your game server and game client builds to work with Amazon GameLift Servers. If you haven't yet integrated your game code, see [Plugin for Unreal: Integrate your game code](unreal-plugin-integrate.md). Enter the paths to your game executables on your local workstation.
+ Game server: Integrate your game server with the server SDK for Amazon GameLift Servers and package your game server build. For instructions, see [Plugin for Unreal: Integrate your game code](unreal-plugin-integrate.md). The game server must be integrated with the server SDK in order to establish communication with the Amazon GameLift Servers service and respond to prompts to start new game sessions and accept game client connections.
+ Game client: At minimum, you need a game client that can connect to your game server using IP address and port information. If you don't yet have your game client components set up for Amazon GameLift Servers, you can use the AWS CLI tool to manually request new game sessions, get connection information, and use that information to connect the game client. 

  At some point, you'll need to have a backend service to send new game sessions requests to the Amazon GameLift Servers service and relay connection information back to a game client. You can use the test maps included with the plugin to add client Amazon GameLift Servers functionality to your game project. For help with building a custom solution, see [Integrate Amazon GameLift Servers game client functionality](gamelift-sdk-client-api.md).

## Step 3: Connect to an Anywhere fleet


In this step, you designate an Anywhere fleet to use. An Anywhere fleet defines a collection of compute resources, which can be located anywhere, for game server hosting.
+ If the AWS account you're currently using has existing Anywhere fleets, open the Fleet name dropdown field and choose a fleet. This dropdown only shows the Anywhere fleets in the AWS Region for the currently active user profile.
+ If there are no existing fleets—or you want to create a new one, choose Create new Anywhere fleet and provide a fleet name.

After you've chosen an Anywhere fleet for your project, Amazon GameLift Servers verifies that fleet status is active and displays the fleet ID. You can track progress of this request in the Unreal editor's output log.

## Step 4: Register your workstation


In this step, you register your local workstation as a compute resource in the new Anywhere fleet.

**To register your workstation as an Anywhere compute**

1. Enter a compute name for your local machine. If you add more than one compute in the fleet, the names must be unique.

1. Provide an IP address for your local machine. This field defaults to your machine's public IP address. You can also use localhost (127.0.0.1) as long as you're running your game client and server on the same machine.

1. Choose Register compute. You can track progress of this request in the Unreal editor's output log.

In response to this action, Amazon GameLift Servers verifies that it can connect to the compute and returns information about the newly registered compute. It also creates the console arguments that your game executables need when initializing communication with the Amazon GameLift Servers service. 

## Step 5: Generate auth token


Game server processes that are running on your Anywhere compute need an authentication token to make calls to the Amazon GameLift Servers service. The plugin automatically generates and stores an auth token for the Anywhere fleet whenever you launch the game server from the plugin. The auth token value is stored as a command line argument, which your server code can retrieve at runtime.

The code examples given above also allow you to use [AWS Signature Version 4 (SigV4) for API requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html). SigV4 is the AWS signing protocol for adding authentication information to API requests.

You do not have to take any action in this step.

## Step 6: Launch game


At this point, you've completed all of the tasks needed to launch and play your multiplayer game on a local workstation using Amazon GameLift Servers. 

**To play your hosted game**

1. Launch your game server. The game server will notify Amazon GameLift Servers when it is ready to host game sessions.

1. Launch your game client and use the new functionality to start a new game session. This request is sent to Amazon GameLift Servers via the new backend service. In response, Amazon GameLift Servers, calls the game server, running on your local machine, to start a new game session. When the game session is ready to accept players, Amazon GameLift Servers provides connection information for the game client to join the game session.

# Plugin for Unreal: Deploy your game to a managed EC2 fleet
Deploy to a managed Amazon EC2 fleet

In this workflow, deploy your game for hosting on cloud-based compute resources managed by Amazon GameLift Servers. Upload your integrated game server build to the Amazon GameLift Servers service for deployment. If you haven't yet integrated your game code, see [Plugin for Unreal: Integrate your game code](unreal-plugin-integrate.md). When this workflow is complete, you'll have a working game client that can connect to your game servers in the cloud. 

**To start the Amazon GameLift Servers managed Amazon EC2 workflow:**
+ In the Unreal editor main toolbar, choose the Amazon GameLift Servers menu, and select **Host with Managed EC2**. This action opens the plugin page **Deploy Amazon EC2 Fleet**, which presents a six-step process to integrate, build, deploy, and launch your game components. 

## Step 1: Set your profile


Choose the profile you want to use when following this workflow. The profile you select impacts all steps in the workflow. All resources you create are associated with the profile's AWS account and are placed in the profile's default AWS Region. The profile user's permissions determine your access to AWS resources and actions.

**To set a user profile**

1. Select a profile from the dropdown list of available profiles. If you don't have a profile yet or want to create a new one, go to the **Amazon GameLift** menu and choose **Set AWS User Profiles**.

1. If bootstrap status is not "Active", choose **Bootstrap profile** and wait for the status to change to "Active".

## Step 2: Set up your game code


In this step, prepare your game server and game client builds to work with Amazon GameLift Servers C\$1\$1 server SDK for Unreal. If you haven't yet integrated your game code and built game client and server executables, see [Plugin for Unreal: Integrate your game code](unreal-plugin-integrate.md). Enter the paths to your game executables on your local workstation.

This step in the workflow the plugin provides links to instructions and source code for setting up a source-built version of the Unreal Editor. You need to use the source-built version when building your client and server components.

After building game server that's integrated with the server SDK, complete the following tasks to prepare it for uploading to Amazon GameLift Servers for hosting.

### To prepare your server build for cloud deployment (Windows)


In the `WindowsServer` folder, where the Unreal editor stores your server build files by default, make the following additions:

1. **Copy the server build install script into the root of the `WindowsServer` folder.** The install script is included in the plugin download. Look for the file `[project-name]/Plugins/Resources/CloudFormation/extra_server_resources/install.bat`. Amazon GameLift Servers uses this file to install the server build onto your hosting computes.

1. **Copy the `VC_redist.x64.exe` file into the root of the `WindowsServer` folder.** You can skip this step if you're using Unreal Engine version 5.6 or later. This file is included in your Visual Studio installation. It is commonly located at `C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC/Redist/MSVC/v142`.

1. **Add the OpenSSL library files to your game server build.**. You can skip this step if your game server is integrated with server SDK 5.3 or later. This version is included in the Amazon GameLift Servers plugin for Unreal, version 3.0 or later. 

   Manually locate and copy the OpenSSL libraries to your game build package directory at `<YourGame>/Binaries/Win64`. You **must** use the same OpenSSL version that your Unreal Engine 5 version uses. Game builds that are deployed with the wrong OpenSSL libraries won't be able to communicate with the Amazon GameLift Servers service.

   Look for the OpenSSL libraries in your game engine source. The location varies depending on your development environment: 

   On 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` 

   On 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`

### To prepare your server build for cloud deployment (Linux)


For more detailed instructions on preparing a game server built for Linux, see [ Building the server SDK for Amazon GameLift Servers for Unreal Engine 5 on Amazon Linux](https://github.com/aws/amazon-gamelift-toolkit/tree/main/building-gamelift-server-sdk-for-unreal-engine-and-amazon-linux).

1. **Designate a working directory to organize your build files.** The working directory's structure is deployed as is onto each hosting compute. Add your Linux-built game server and all dependent files. 

1. **Create a server build install script in the root of your working directory.** If needed,create an `install.sh` file and add any commands needed to properly install your game server build. Amazon GameLift Servers uses this file to install the server build onto each EC2 hosting resource.

1. **Add the OpenSSL library files to your game server build.** You can skip this step if your game server is integrated with server SDK 5.3 or later. 

   Manually locate and copy the libraries. You **must** use the same OpenSSL version that your Unreal Engine 5 version uses. Game builds that are deployed with the wrong OpenSSL libraries won't be able to communicate with the Amazon GameLift Servers service.

   1. Look for the OpenSSL libraries in your game engine source. The location varies depending on your development environment: 

      On 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` 

      On 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`

   1. When you locate the OpenSSL libraries, copy them to your game build package directory at `<YourGame>/Binaries/Linux`. 

## Step 3: Select deployment scenario


In this step, you choose the game hosting solution that you want to deploy at this time. You can have multiple deployments of your game, using any of the scenarios. 
+ Single-region fleet: Deploys your game server to a single fleet of hosting resources in the active profile's default AWS region. This scenario is a good starting point for testing your server integration with AWS and server build configuration. It deploys the following resources:
  + AWS fleet (On-Demand) with your game server build installed and running.
  + Amazon Cognito user pool and client to enable players to authenticate and start a game.
  + API gateway authorizer that links user pool with APIs.
  + WebACl for throttling excessive player calls to API gateway.
  + API gateway \$1 Lambda function for players to request a game slot. This function calls `CreateGameSession()` if none are available.
  + API gateway \$1 Lambda function for players to get connection info for their game request.
+ FlexMatch fleet: Deploys your game server to a set of fleets and sets up a FlexMatch matchmaker with rules to create player matches. This scenario uses low-cost Spot hosting with a multi-fleet, multi-location structure for durable availability. This approach is useful when you're ready to start designing a matchmaker component for your hosting solution. In this scenario, you'll create the basic resources for this solution, which you can customize later as needed. It deploys the following resources:
  + FlexMatch matchmaking configuration and matchmaking rule set to accept player requests and form matches.
  + Three AWS fleets with your game server build installed and running in multiple locations. Includes two Spot fleets and one On-Demand fleet as a backup. 
  + AWS game session placement queue that fulfills requests for proposed matches by finding the best possible hosting resource (based on viability, cost, player latency, etc.) and starting a game session.
  + Amazon Cognito user pool and client to enable players to authenticate and start a game.
  + API gateway authorizer that links user pool with APIs.
  + WebACl for throttling excessive player calls to API gateway.
  + API gateway \$1 Lambda function for players to request a game slot. This function calls `StartMatchmaking()`.
  + API gateway \$1 Lambda function for players to get connection info for their game request.
  + Amazon DynamoDB tables to store matchmaking tickets for players and game session information.
  + SNS topic \$1 Lambda function to handle GameSessionQueue events.

## Step 4: Set game parameters


In this step, you describe your game for uploading to AWS;
+ Server build name: Provide a meaningful name for your game server build. AWS uses this name to refer to the copy of your server build that's uploaded and used for deployments.
+ Server build OS: Enter the operating system that your server is built to run on. This tells AWS what type of compute resources to use to host your game.
+ Game server folder: Identify the path to your local server build folder.
+ Game server build: Identify the path to the game server executable.
+ Game client path: Identify the path to the game client executable.
+ Client configuration output: This field needs to point to a folder in your client build that contains your AWS configuration. Look for it in the following location: `[client-build]/[project-name]/Content/CloudFormation`. 

## Step 5: Deploy scenario


In this step, you deploy your game to a cloud hosting solution based on the deployment scenario you chose. This process can take several minutes while AWS validates your server build, provisions hosting resources, installs your game server, launches server processes, and gets them ready to host game sessions.

To start deployment, choose **Deploy CloudFormation**. You can track the status of your game hosting here. For more detailed information, you can sign in to the AWS Management console for AWS and view event notifications. Be sure to sign in using the same account, user, and AWS Region as the active user profile in the plugin.

When deployment is complete, you have your game server installed on an AWS EC2 instance. At least one server process is running and ready to start a game session. 

## Step 6: Launch client


At this point, you've completed all of the tasks needed to launch and play your multiplayer game hosted with Amazon GameLift Servers. To play the game, launch an instance of your game client. 

If you deployed the single fleet scenario, you can open a single client instance with one player, enter the server map and move around. Open additional instances of the game client to add a second player to the same server game map. 

If you deployed the FlexMatch scenario, the solution waits for at least two clients to be queued for game session placement before the players can enter the server map.

# Plugin for Unreal: Deploy your game to a managed container fleet
Deploy to a managed container fleet

Use this guided plugin workflow to create a container image for your game server and deploy it to a container-based hosting solution. If you haven't yet integrated your game code, see [Plugin for Unreal: Integrate your game code](unreal-plugin-integrate.md). When you’ve successfully completed this workflow, your containerized game server is running in the cloud, and you can use the plugin to start a game client, connect to a game session, and play the game.

## Before you start


This workflow assumes that you’ve completed the following tasks. 
+ **Integrate your game server code with Amazon GameLift Servers server SDK.** Your hosted game server must be able to communicate with the Amazon GameLift Servers service so that it can respond to requests to start new game sessions and report game session status. If you haven’t completed this task, we recommend that you follow the plugin workflow Host with Anywhere first. For guidance on preparing your game server code, see [Update your game server code](unreal-plugin-integrate.md#unreal-plugin-anywhere-integrate-simple-server). For a managed container fleet, you must integrate your game with server SDK version 5.2 or higher.
**Note**  
If you're using the startup game map, this task is already done for you. 
+ **Package your game server executable to run on Linux.** If you’re developing on Windows and integrating C\$1\$1 server SDK version 5.2.x or earlier, you’ll need to work with the [ Unreal cross compile toolkit](http://cross-compile toolkit for your UE version). Alternatively, you might set up a separate Linux workspace or use a tool such as Windows subsystem for Linux (WSL). 
+ **Gather files to deploy with your game server build.** On your local machine, create a working directory to organize the files, which will be built into your game server container image. These might include game dependencies, a script to launch game servers and other processes when starting a container, etc. 
+ **Add the OpenSSL library files for your game server build.** You can skip this step if your game server is integrated with server SDK 5.3 or later. 

  Manually locate and copy the OpenSSL libraries to your game build package directory at `<YourGame>/Binaries/Win64`. You **must** use the same OpenSSL version that your Unreal Engine 5 version uses. Game builds that are deployed with the wrong OpenSSL libraries won't be able to communicate with the Amazon GameLift Servers service.

  To find the OpenSSL libraries, look in your game engine source. The location varies depending on your development environment: 

  On 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` 

  On 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`
+ **Integrate your game client code with Amazon GameLift Servers.** One way to complete this task is to add a sample asset (included with the plugin) that’s already integrated. For guidance on preparing your game client code, see [Integrate your client game map](unreal-plugin-integrate.md#unreal-plugin-anywhere-integrate-simple-client). 
+ **Install Docker on your local machine.** You need this tool installed if you want the plugin to create container images for you and push them to an ECR repository. Alternatively you can do these tasks manually and instruct the plugin to use an existing container image. For more information about building your image manually, see [ Build a container image for Amazon GameLift Servers](https://docs.aws.amazon.com/gameliftservers/latest/developerguide/containers-prepare-images.html).

**To start the Amazon GameLift Servers managed containers workflow:**
+ In the Unreal editor main toolbar, choose the Amazon GameLift Servers menu, and select **Managed Containers**. This action opens the plugin page **Host with Managed Containers**, which presents a step-by-step process to create a container image with your game server build, deploy it to a container fleet, and launch your game. 

## Step 0: Set your profile


This section displays your currently selected user profile. Verify that the current user profile is the one you want to use for this workflow. All the resources that you create in this workflow are associated with the profile's AWS account and are placed in the profile's default AWS Region. The profile user's permissions determine your access to AWS resources and actions.

You might need to modify the selected user profile if: 
+ No profile is currently selected.
+ You want to select a different profile or create a new profile.
+ You need to bootstrap the selected profile (if bootstrap status is inactive).

**To set or change the selected user profile**
+ In the Amazon GameLift Servers menu, choose **Open AWS Access Credentials**.

## Step 1: Assess container readiness


Before deploying your game server to a container fleet, you must package it into a container image and store in an Amazon ECR repository. The plugin can complete these tasks for you or you can do these tasks manually. In this step, provide information about the status of your container image and the ECR repository. 

Use the assessment questions to tell the plugin what steps it needs to take: 
+ **Create a new container image.** If you choose this option, the next step will prompt you for the location of your game server build directory and the build executable. The plugin uses a Dockerfile template (supplied by Amazon GameLift Servers) and automatically configures it for your game. You can view the template at [Build a container image for Amazon GameLift Servers](containers-prepare-images.md). After choosing this option, indicate where you want the plugin to store the new image:
  + Create a new Amazon ECR repository and push the container image to it. The plugin creates a private ECR repo using the AWS account and default AWS Region in your selected user profile.
  + Push the container image to a previously created Amazon ECR repository. If you choose this option, the next step will prompt you to select an existing Amazon ECR repository from a list. The list includes all Amazon ECR repositories for the AWS account and default AWS Region in your selected user profile. You can select a public or private repository.
+ **Use an existing container image.** If you've manually built an image, we recommend that you use the Dockerfile template supplied by Amazon GameLift Servers, which is available at [Build a container image for Amazon GameLift Servers](containers-prepare-images.md). After choosing this option, indicate where the image is located. 
  + A locally stored Docker-generated image. If you choose this option, the plugin creates a new Amazon ECR private repository and pushes the local image file to it. The next step will prompt you for an image ID, which the plugin uses to locate the image file.
  + A container image that's already stored in an Amazon ECR repository. If you choose this option, the next step will prompt you to select an existing Amazon ECR repository and image from a list. The list includes all Amazon ECR repositories for the AWS account and default AWS Region in your selected user profile. You can select a public or private repository.

## Step 2: Configure image deployment


In this step, provide information that the plugin needs to deploy your container image to a container fleet. This step requests the following information: 
+ The location of your game server build, container image, or Amazon ECR repository, based on your selections in Step 1. 
+ The scenario to use for your managed containers deployment.
+ The client configuration output path. Select the folder in your client build that contains your AWS configuration. Look for it in the following location: `[client-build]/[project-name]/Content/CloudFormation`. 
+ Optional deployment settings. This section has configuration settings that the plugin uses by default. You can modify these or keep the default values
  + Game name is set to the name of your game project by default. All AWS resources that the plugin creates references the game name value.
  + Port range, memory limit, and vCPU limit are configuration settings for the container fleet. For more information about customizing these values, see [Configure network connections](containers-design-fleet.md#containers-custom-network) for connection port range, and [Set resource limits](containers-design-fleet.md#containers-design-fleet-limits) for resource limits.
  + Container image tag is used to categorize your container images in Amazon ECR. The default value is `unreal-gamelift-plugin`.
  + Name of the Amazon ECR repository. You can edit this field to suggest a custom name only when the plugin is creating an ECR repository for you. The default value is `unreal-game lift-plugin-ecr-repository`.

### Deployment scenario options


#### Single-region container fleet


This scenario deploys your game server to a single container fleet. It's a good starting point for testing your server integration with AWS and your container configuration. It deploys the following resources. 
+ Amazon GameLift Servers container group definition describes how to deploy and run your container images on a container fleet. 
+ Amazon GameLift Servers container fleet (On-Demand) with your game server container installed and running, with alias.
+ Amazon Cognito user pool and client to enable players to authenticate and start a game.
+ API Gateway authorizer that links the user pool with APIs.
+ Web access control list (ACL) for throttling excessive player calls to API Gateway.
+ Backend service to make requests to the Amazon GameLift Servers service on behalf of game clients, such as to request game sessions and join games: 
  + API Gateway \$1 Lambda function for players to request a game session slot. This function calls `CreateGameSession()` if no open slots are available.
  + API Gateway \$1 Lambda function for players to get connection info for their game request.

#### Single-region container fleet with FlexMatch


This scenario deploys your game server to a container fleet, configures game session placement, and sets up FlexMatch matchmaking. This scenario is useful when you're ready to start designing a custom matchmaker for your hosting solution. Use this scenario to create the basic resources for this solution, which you can customize later as needed. It deploys the following resources:
+ Amazon GameLift Servers container group definition that describes how to deploy and run your container images on a container fleet. 
+ Amazon GameLift Servers container fleet (On-Demand) with your game server container installed and running, with alias.
+ FlexMatch matchmaking configuration and matchmaking rule set to accept player requests and form matches.
+ Amazon GameLift Servers game session queue that fulfills requests for proposed matches by finding the best possible hosting resource (based on viability, cost, player latency, etc.) and starting a game session.
+ Amazon Cognito user pool and client to enable players to authenticate and start a game.
+ API Gateway authorizer that links the user pool with APIs.
+ Web access control list (ACL) for throttling excessive player calls to API Gateway.
+ Backend service to make requests to the Amazon GameLift Servers service on behalf of game clients, such as to request game sessions and join games: 
  + API Gateway \$1 Lambda function for players to request a game session slot. This function calls `StartMatchmaking()` if no open slots are available.
  + API Gateway \$1 Lambda function for players to get connection info for their game request.
+ DynamoDB tables to store matchmaking tickets for players and game session information.
+ Amazon SNS topic \$1 Lambda function to handle GameSessionQueue events.

## Deploy container fleet


When your fleet configuration is complete, choose the **Deploy container fleet** button to start deployment. This process can take several minutes while the plugin creates a container image and pushes it to ECR, provisions hosting resources for the container fleet, deploys the fleet and other AWS resources for the selected hosting solution scenario. 

When you start a deployment, you can track the progress of each step. Depending on your configuration, the steps might include the following: 
+ Configuring container image
+ Creating an Amazon ECR repository 
+ Building an image and pushing to Amazon ECR
+ Creating container group definition
+ Creating container fleet

For more detailed deployment information, choose **View in AWS Management Console**. When the container fleet reaches active status, the fleet is actively running containers with server processes that are ready to host game sessions.

When deployment is complete, you have a working container fleet that’s ready to host game sessions and accept player connections. 

You can’t stop a deployment in progress. If the deployment enters a bad state or fails, you can start over by using the **Reset deployment** option.

## Launch client


At this point, you've completed all the tasks to launch and play your multiplayer game hosted with Amazon GameLift Servers. To play your game, choose **Start Client** to launch a local instance of your game client. 
+ If you deployed the single fleet scenario, open one instance of your game client with one player and enter the server map to move around. You can open a second instance of the game client to add a second player to the same server game map.
+ If you deployed the FlexMatch scenario, the hosting solution waits for at least two game clients to make matchmaking requests. Open at least two instances of your game client with one player. The two players will be matched and prompted to join a game session for the match. 

## Update a container fleet


If you've successfully deployed a managed containers hosting solution, you can use the **Update deployment**feature. This option lets you update configuration settings for a deployed container fleet, without having to create a new fleet. 

When updating a deployment, you can deploy a container image with a different game server build, change the Amazon ECR repository, choose a different deployment scenario, and customize optional configuration settings.

When you're ready to deploy your changes, choose Update. The time required for a deployment update is similar to a full deployment. For detailed deployment information, choose **View in AWS Management Console**.

## Clean up deployed resources


As a best practice, clean up the AWS resources for your managed containers solution as soon as you no longer need them. You might continue to incur costs for these resources if you don't remove them.

Delete the following resources:
+ Managed container resource stack. The resources in this stack depends on the deployment scenario you selected. To delete the entire stack, use the CloudFormation console. Stacks that are generated from the Amazon GameLift Servers plugin use the following naming convention: `GameLiftPluginForUnreal-{GameName}-Containers`. Wait for the stack deletion process to complete before you initiate a new managed containers deployment in the plugin. For more information, see [ Delete a stack from the CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html).
+ Amazon ECR repository. If you used the plugin to create a repository for your container image, you might want to delete any repositories that are no longer needed. You don't need to delete a repository before resetting a managed containers deployment. If you update or reset a deployment, the plugin will automatically use the same repository unless directed to use another one. For more information, see [ Deleting a private repository in Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-delete.html).

# Amazon GameLift Servers plugin for Unity (server SDK 5.x)
Plugin for Unity (server SDK 5.x)

This plugin adds the Amazon GameLift Servers C\$1 server SDK and tools to the Unity editor. Use the guided UI workflows to integrate server SDK functionality into your game project and deploy an Amazon GameLift Servers hosting solution for your game server. 

With the plugin, you can build a basic working hosting solution and then optimize and customize as needed. Set up an Amazon GameLift Servers Anywhere fleet with your local workstation as a host. For cloud hosting with managed EC2 or managed container fleets, deploy your game server with a complete solution to manage game session requests and client connections.

**Topics**
+ [

## Install the plugin for your Unity game project
](#unity-plugin-install)
+ [

# Plugin for Unity: Set up an AWS user profile
](unity-plug-in-profiles.md)
+ [

# Plugin for Unity: Set up local testing with Amazon GameLift Servers Anywhere
](unity-plug-in-anywhere.md)
+ [

# Plugin for Unity: Deploy your game to a managed EC2 fleet
](unity-plug-in-ec2.md)
+ [

# Plugin for Unity: Deploy your game to a managed container fleet
](unity-plug-in-container.md)

## Install the plugin for your Unity game project
Install the plugin

**[ Get the Amazon GameLift Servers plugin for Unity from GitHub](https://github.com/amazon-gamelift/amazon-gamelift-plugin-unity)**

See the GitHub repository readme for information about how to install the plugin for a game project. 

The plugin includes these components: 
+ Plugin modules for the Unity editor. When the plugin is installed, a new main menu item gives you access to Amazon GameLift Servers functionality.
+ C\$1 libraries for the Amazon GameLift Servers service API with client-side functionality. 
+ C\$1 libraries for the Amazon GameLift Servers server SDK (version 5.x).
+ Sample game content, including assets and scenes, so you can try out Amazon GameLift Servers even if you don't have a build-ready multiplayer game.
+ Solution configurations, provided as CloudFormation templates, that the plugin uses when deploying your game server to the cloud for hosting.

This plugin uses AWS CloudFormation templates to deploy hosting solutions for common gaming scenarios. Use these solutions as provided or customize them as needed for your games.

# Plugin for Unity: Set up an AWS user profile
Set up an AWS user profile

After installing the plugin, set up a user profile with a valid AWS account. You can maintain multiple profiles in the plugin, but you can have only one profile selected at a time. Whenever you work in the plugin, select a profile to use. Each workflow page displays the currently selected profile. 

Maintaining multiple profiles gives you the ability to switch between different hosting deployments. For example, you might set up profiles that use the same AWS account but deploy to different AWS Regions. Or you might set up profiles with different AWS accounts or users and permission sets.

**Note**  
If you've installed the AWS CLI on your workstation and have a profile already configured, the Amazon GameLift Servers plugin will detect it and list it as an existing profile. The plugin automatically selects any profile named `[default]`. You can use an existing profile or create a new one. 

All profiles must be bootstrapped to set up some required AWS resources under your account user.

**To manage your AWS profiles**

1. In the Unity main toolbar, choose the Amazon GameLift Servers menu, and select **AWS Access Credentials**. This action opens the Amazon GameLift Servers plugin to the page **Set up your user profile**.

1. Use the buttons to create a new AWS account or set up a user profile for an AWS account that you already have. 

1. If you don't already have a user profile, you're prompted to enter profile details and create a new profile. Provide the following information:
   + An AWS account. If you create a new AWS account, use the link to the AWS Management Console and follow the prompts. See [ Create an AWS account](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html) for more details.
   + An AWS user with permissions to use Amazon GameLift Servers and other required AWS services. See [Set up an AWS user account](setting-up-aws-login.md) for instructions on setting up an AWS Identity and Access Management (IAM) user with Amazon GameLift Servers permissions and programmatic access with long-term credentials.
   + Credentials for your AWS user. These credentials consist of an AWS access key ID and AWS secret key. See [ Get your access keys](https://docs.aws.amazon.com/cli/latest/userguide/cli-authentication-user.html#cli-authentication-user-get) for more details.
   + AWS region. This is a geographic location where you want to create your AWS resources for hosting. During development, we recommend using a region close to your physical location. Choose a region from the list of [ supported AWS regions](https://docs.aws.amazon.com/general/latest/gr/gamelift.html).

1. If the plugin detects existing profiles, it displays a list of available profiles. Select an existing profile from the list, or choose **Add another profile** to create a new one. 

## Bootstrap a user profile


All profiles must be bootstrapped to use with the Amazon GameLift Servers plugin. Bootstrapping creates an Amazon S3 bucket specific to the profile. It's used to store project configurations, build artifacts, and other dependencies. Buckets are not shared between other profiles.

Bootstrapping involves creating new AWS resources and might incur costs.

**To bootstrap your profile:**

1. On the **AWS Access Credentials** page, check the bootstrap status of the user profile that you wan to use. If the profile's bootstrap status is "Inactive" and there's no S3 bucket listed, you need to bootstrap the profile. 

1. Select the profile you want to use and choose **Bootstrap profile**. 

1. Wait for bootstrap status to change to "Active". This can take a few minutes.

# Plugin for Unity: Set up local testing with Amazon GameLift Servers Anywhere
Set up local testing with Anywhere

In this workflow, you add client and server game code for Amazon GameLift Servers functionality and use the plugin to designate your local workstation as a test game server host. When you've completed integration tasks, use the plugin to build your game client and server components.

**To start the Amazon GameLift Servers Anywhere workflow:**
+ In the Unity editor main menu, choose **Amazon GameLift Servers** and select **Host with Anywhere**. This action opens the plugin page for setting up your game with an @Anywhere fleet. The page presents a five-step process to integrate, build, and launch your game components. 

## Set your profile


Choose the profile you want to use when following this workflow. The profile you select impacts all steps in the workflow. All resources you create are associated with the profile’s AWS account and are placed in the profile’s default AWS Region. The profile user’s permissions determine your access to AWS resources and actions.

1. Select a profile from the dropdown list of available profiles. If you don’t have a profile yet or want to create a new one, go to the **Amazon GameLift Servers** menu and choose **Set AWS Account Profiles**.

1. If bootstrap status is not “Active“, choose **Bootstrap profile** and wait for the status to change to “Active“.

## Integrate your game code with the C\$1 server SDK
Integrate your game code

**Note**  
If you imported the sample game, you can skip this step. The sample game assets already have the necessary server and client code in place. 

For this step in the workflow, you make updates to the client and server code in your game project. 
+ Game servers must be able to communicate with the Amazon GameLift Servers service to receive prompts to start a game session, provide game session connection information, and report status. 
+ Game clients must be able to get information about game sessions, join or start game sessions, and get connection information to join a game.

### Integrate your server code


If you’re using your own game project with custom scenes, use provided sample code to add required server code to your game project:

1. In your game project files, open the `Assets/Scripts/Server` folder. If it doesn’t exist, create it.

1. Go to the GitHub repo [ aws/amazon-gamelift-plugin-unity](https://github.com/aws/amazon-gamelift-plugin-unity) and open the path `Samples~/SampleGame/Assets/Scripts/Server`.

1. Locate the file `GameLiftServer.cs` and copy it into your game project’s `Server` folder. When you build a server executable, use this file as the build target.

The sample code includes these minimum required elements, which use Amazon GameLift Servers C\$1 server SDK (version 5): 
+ Initializes an Amazon GameLift Servers API client. The `InitSDK()` call with server parameters is required for an Amazon GameLift Servers Anywhere fleet. These settings are automatically set for use in the plugin.
+ Implements required callback functions to respond to requests from the Amazon GameLift Servers service, including `OnStartGameSession`, `OnProcessTerminate`, and `onHealthCheck`.
+ Calls `ProcessReady()` with a designated port to notify the Amazon GameLift Servers service when the server process is ready to host game sessions.

If you want to customize the sample server code, see these resources: 
+ [Add Amazon GameLift Servers to your game server with the server SDK](gamelift-sdk-server-api.md)
+ [C\$1 server SDK 5.x for Amazon GameLift Servers -- Actions](integration-server-sdk5-csharp-actions.md)

### Integrate your client code


If you’re using your own game project with custom scenes, then you need to integrate basic functionality into your game client. You also need to add UI elements so that players can sign in and join a game session. Use the service API for Amazon GameLift Servers (in the AWS SDK) to get game session information, create new game sessions, or join existing game sessions, 

When building a client for local testing with an Anywhere fleet, you can add direct calls to the Amazon GameLift Servers service. When you develop your game for cloud hosting—or if you plan to use Anywhere fleets for production hosting—you’ll need to create a client-side backend service to handle all communication between game clients and the Amazon GameLift Servers service. 

To integrate Amazon GameLift Servers into your client code, use the following resources as a guide.
+ Integrate the client with the GameLiftCoreApi class in the GitHub repo aws/amazon-gamelift-plugin-unity. This class provides controls for player authentication and for retrieving game session information.
+ View sample game integrations, available in the GitHub repo aws/amazon-gamelift-plugin-unity, `Samples~/SampleGame/Assets/Scripts/Client/GameLiftClient.cs`.
+ Follow instructions in Add Amazon GameLift Servers to your Unity game client.

For game clients connecting to an Anywhere fleet, your game client needs the following information. The plugin automatically updates your game project to use the resources that your create in the plugin.
+ FleetId - The unique identifier for your Anywhere fleet.
+ FleetLocation - The custom location of your Anywhere fleet.
+ AwsRegion - The AWS region where your Anywhere fleet is hosted. This is the region you set in your user profile.
+ ProfileName - An AWS credentials profile on your local machine that allows access to the AWS SDK for Amazon GameLift Servers . The game client uses these credentials to authenticate requests to the Amazon GameLift Servers service.

**Note**  
The credentials profile is generated by the plugin and stored on the local machine. As a result, you must run the client on the local machine (or on a machine with the same profile).

## Connect to an Anywhere fleet


In this step, you designate an Anywhere fleet to use. An Anywhere fleet defines a collection of compute resources, which can be located anywhere, for game server hosting.
+ If the AWS account you’re currently using has existing Anywhere fleets, open the **Fleet name** dropdown field and choose a fleet. This dropdown only shows the Anywhere fleets in the AWS Region for the currently active user profile.
+ If there are no existing fleets—or you want to create a new one, choose **Create new Anywhere fleet** and provide a fleet name.

After you’ve chosen an Anywhere fleet for your project, Amazon GameLift Servers verifies that fleet status is active and displays the fleet ID. You can track progress of this request in the Unity editor’s output log.

## Register a compute


In this step, you register your local workstation as a compute resource in the new Anywhere fleet.

1. Enter a compute name for your local machine. If you add more than one compute in the fleet, the names must be unique.

1. Choose **Register compute**. You can track progress of this request in the Unity editor’s output log.

The plugin registers your local workstation with the IP address set to localhost (127.0.0.1). This setting assumes that you’ll run your game client and server on the same machine.

In response to this action, Amazon GameLift Servers verifies that it can connect to the compute and returns information about the newly registered compute. 

## Launch game


In this step you build your game components and launch them to play the game. Complete the following tasks:

1. Configure your game client. In this step, you prompt the plugin to update a `GameLiftClientSettings` asset for your game project. The plugin uses this asset to store certain information that your game client needs to connect to the Amazon GameLift Servers service. 

   1. If you didn’t import and initialize the sample game, create a new `GameLiftClientSettings` asset. In the Unity editor main menu, choose **Assets, Create, Amazon GameLift, Client Settings**. If you create multiple copies of `GameLiftClientSettings` in your project, the plugin automatically detects this and notifies you which asset the plugin will update.

   1. In **Launch Game**, choose **Configure Client: Apply Anywhere Settings**. This action updates your game client settings to use the Anywhere fleet that you just set up.

1. Build and run your game client.

   1. Build a client executable using the standard Unity build process. In **File, Build Settings**, switch the platform to **Windows, Mac, Linux**. If you imported the sample game and initialized the settings, the build list and build target are automatically updated. 

   1. Launch one or more instances of the newly built game client executable. 

1. Launch a game server in your Anywhere fleet. Choose **Server: Launch Server** in Editor. This task starts a live server that your client can connect to as long as the Unity editor remains open.

1. Start or join a game session. In your game client instances, use the UI to join each client to a game session. How you do this depends on how you added functionality to the client.

If you're using the sample game client, it has the following characteristics:
+ A player login component. When connecting to a game server on an Anywhere fleet, there is no player validation. You can enter any values to join the game session.
+ A simple join game UI. When a client attempts to join a game, the client automatically looks for an active game session with an available player slot. If no game session is available, the client requests a new game session. If a game session is available, the client requests to join the available game session. When testing your game with multiple concurrent clients, the first client starts the game session, and the remaining clients automatically join the existing game session.
+ Game sessions with four player slots. You can launch up to four game client instances concurrently and they will join the same game session. 

**Launch from a server executable (optional)**

You can build and launch your game server executable for testing on an Anywhere fleet.

1. Build a server executable using the standard Unity build process. In **File, Build Settings**, switch the platform to **Dedicated Server** and build.

1. Get a short-term authentication token by calling the AWS CLI command [get-compute-auth-token](https://docs.aws.amazon.com/cli/latest/reference/gamelift/get-compute-auth-token.html) with your Anywhere fleet ID and AWS Region. The fleet ID is displayed in **Connect to an Anywhere Fleet** when you create the fleet. The AWS Region is displayed in **Set Your Profile** when you select your active profile.

   ```
   aws gamelift get-compute-auth-token --fleet-id [your anywhere fleet ID] --region [your AWS region]
   ```

1. Launch the newly built game server executable from a command line and pass in a valid auth token.

   ```
   my_project.exe --authToken [token]
   ```

# Plugin for Unity: Deploy your game to a managed EC2 fleet
Deploy to a managed Amazon EC2 fleet

In this workflow, you use the plugin to prepare your game for hosting on cloud-based compute resources that are managed by Amazon GameLift Servers. You add client and server game code for Amazon GameLift Servers functionality, then upload your server build to the Amazon GameLift Servers service for hosting. When this workflow is complete, you’ll have game servers running in the cloud and a working game client that can connect to them. 

**To start the Amazon GameLift Servers managed Amazon EC2 workflow:**
+ In the Unity editor main menu, choose **Amazon GameLift Servers** and select **Host with Managed EC2**. This workflow presents a six-step process to integrate, build, deploy, and launch your game components. 

## Set your profile


Choose the profile you want to use when following this workflow. The profile you select impacts all steps in the workflow. All resources you create are associated with the profile’s AWS account and are placed in the profile’s default AWS Region. The profile user’s permissions determine your access to AWS resources and actions.

1. Select a profile from the dropdown list of available profiles. If you don’t have a profile yet or want to create a new one, go to the Amazon GameLift Servers menu and choose **Set AWS Account Profiles**.

1. If bootstrap status is not “Active“, choose **Bootstrap profile** and wait for the status to change to “Active“.

## Integrate your game with Amazon GameLift Servers
Integrate your game

For this task, you make updates to the client and server code in your game project. 
+ Game servers must be able to communicate with the Amazon GameLift Servers service to receive prompts to start a game session, provide game session connection information, and report status. 
+ Game clients must be able to get information about game sessions, join or start game sessions, and get connection information to join a game.

**Note**  
If you imported the sample game, you can skip this step. The sample game assets already have the necessary server and client code in place. 

### Integrate your server code


When using your own game project with custom scenes, use the provided sample code to add required server code to your game project. If you integrated your game project for testing with an Anywhere fleet, you’ve already completed the instructions in this step.

1. In your game project files, open the `Assets/Scripts/Server` folder. If it doesn’t exist, create it.

1. Go to the GitHub repo [ aws/amazon-gamelift-plugin-unity](https://github.com/aws/amazon-gamelift-plugin-unity) and open the path `Samples~/SampleGame/Assets/Scripts/Server`.

1. Locate the file `GameLiftServer.cs` and copy it into your game project’s `Server` folder. When you build a server executable, use this file as the build target.

The sample code includes these minimum required elements, which use Amazon GameLift Servers C\$1 server SDK (version 5): 
+ Initializes an Amazon GameLift Servers API client. The InitSDK() call with server parameters is required for an Amazon GameLift Servers Anywhere fleet. These settings are automatically set for use in the plugin.
+ Implements required callback functions to respond to requests from the Amazon GameLift Servers service, including `OnStartGameSession`, `OnProcessTerminate`, and `onHealthCheck`.
+ Calls `ProcessReady()` with a designated port to notify the Amazon GameLift Servers service when the server process is ready to host game sessions.

If you want to customize the sample server code, see these resources: 
+ [Add Amazon GameLift Servers to your game server with the server SDK](gamelift-sdk-server-api.md)
+ [C\$1 server SDK 5.x for Amazon GameLift Servers -- Actions](integration-server-sdk5-csharp-actions.md)

### Integrate your client code


For game clients that connect to cloud-based game servers, it’s a best practice to use a client-side backend service to make calls to the Amazon GameLift Servers service, instead of making the calls directly from the game client. 

In the plugin workflow for hosting on a managed EC2 fleet, each deployment scenario includes a pre-built backend service that includes the following components: 
+ A set of Lambda functions and DynamoDB tables that are used to request game sessions and retrieve game session information. These components use an API gateway as the proxy.
+ An Amazon Cognito user pool that generates unique player IDs and authenticates player connections.

To use these components, your game client needs functionality to send requests to the backend service to do the following: 
+ Create a player user in the AWS Cognito user pool and authenticate.
+ Join a game session and receive connection information.
+ Join a game using matchmaking.

Use the following resources as a guide. 
+ Integrate the client with the [ GameLiftCoreApi](https://github.com/aws/amazon-gamelift-plugin-unity/blob/main/Runtime/GameLiftCoreApi.cs) class in the GitHub repo [ aws/amazon-gamelift-plugin-unity](https://github.com/aws/amazon-gamelift-plugin-unity). This class provides controls for player authentication and for retrieving game session information. 
+ To view the sample game integrations go to the GitHub repo [aws/amazon-gamelift-plugin-unity ](https://github.com/aws/amazon-gamelift-plugin-unity), `Samples~/SampleGame/Assets/Scripts/Client/GameLiftClient.cs`.
+ [Integrate Amazon GameLift Servers game client functionality](gamelift-sdk-client-api.md).

### (Unity 6.3\$1 Only) Integrate install.sh script


Unity 6.3 on Linux requires glibc 2.35. Amazon Linux 2023 includes glibc 2.34. An install.sh script is provided which handles building glibc 2.35 from source and configuring the Unity binaries to use glibc 2.35.

1. Go to the GitHub repo [ aws/amazon-gamelift-plugin-unity](https://github.com/aws/amazon-gamelift-plugin-unity) and open the path `ExtraServerResources`.

1. Locate the file `install.sh` and copy it into the folder containing your server build.

1.  If you have an existing `install.sh`, merge the contents of both scripts into a single `install.sh`. 

## Select deployment scenario


In this step, you choose the game hosting solution that you want to deploy at this time. You can have multiple deployments of your game, using any of the scenarios. 
+ **Single-region fleet:** Deploys your game server to a single fleet of hosting resources in the active profile’s default AWS region. This scenario is a good starting point for testing your server integration with AWS and server build configuration. It deploys the following resources:
  + AWS fleet (On-Demand) with your game server build installed and running.
  + Amazon Cognito user pool and client to enable players to authenticate and start a game.
  + API gateway authorizer that links user pool with APIs.
  + WebACl for throttling excessive player calls to API gateway.
  + API gateway \$1 Lambda function for players to request a game slot. This function calls `CreateGameSession()` if none are available.
  + API gateway \$1 Lambda function for players to get connection info for their game request.
+ **FlexMatch fleet:** Deploys your game server to a set of fleets and sets up a FlexMatch matchmaker with rules to create player matches. This scenario uses low-cost Spot hosting with a multi-fleet, multi-location structure for durable availability. This approach is useful when you're ready to start designing a matchmaker component for your hosting solution. In this scenario, you'll create the basic resources for this solution, which you can customize later as needed. It deploys the following resources:
  + FlexMatch matchmaking configuration and matchmaking rule set to accept player requests and form matches.
  + Three AWS fleets with your game server build installed and running in multiple locations. Includes two Spot fleets and one On-Demand fleet as a backup. 
  + AWS game session placement queue that fulfills requests for proposed matches by finding the best possible hosting resource (based on viability, cost, player latency, etc.) and starting a game session.
  + Amazon Cognito user pool and client to enable players to authenticate and start a game.
  + API gateway authorizer that links user pool with APIs.
  + WebACl for throttling excessive player calls to API gateway.
  + API gateway \$1 Lambda function for players to request a game slot. This function calls `StartMatchmaking()`.
  + API gateway \$1 Lambda function for players to get connection info for their game request.
  + Amazon DynamoDB tables to store matchmaking tickets for players and game session information.
  + SNS topic \$1 Lambda function to handle GameSessionQueue events.

## Set game parameters


In this step, you describe your game for uploading to AWS.
+ **Game name:** Provide a meaningful name for your game project. This name is used within the plugin.
+ **Fleet name:** Provide a meaningful name for your managed EC2 fleet. Amazon GameLift Servers uses this name (along with the fleet ID) when listing resources in the AWS console.
+ **Build name:** Provide a meaningful name for your server build. AWS uses this name to refer to the copy of your server build that’s uploaded to Amazon GameLift Servers and used for deployments.
+ **Launch parameters:** Enter optional instructions to run when launching the server executable on a managed EC2 fleet instance. Maximum length is 1024 characters.
+ **Game server folder:** Provide the path to a local folder containing your server build.
+ **Game server file:** Specify the server executable file name.

## Deploy scenario


In this step, you deploy your game to a cloud hosting solution based on the deployment scenario you chose. This process can take several minutes while AWS validates your server build, provisions hosting resources, installs your game server, launches server processes, and gets them ready to host game sessions.

To start deployment, choose **Deploy CloudFormation**. You can track the status of your game hosting here. For more detailed information, you can sign in to the AWS Management console for AWS and view event notifications. Be sure to sign in using the same account, user, and AWS Region as the active user profile in the plugin.

When deployment is complete, you have your game server installed on an AWS EC2 instance. At least one server process is running and ready to start a game session. 

## Launch game client


When your fleet is successfully deployed, you now have game servers running and available to host game sessions. You can now build your client, launch it, connect to join the game session. 

1. Configure your game client. In this step, you prompt the plugin to update a `GameLiftClientSettings` asset for your game project. The plugin uses this asset to store certain information that your game client needs to connect to the Amazon GameLift Servers service. 

   1. If you didn’t import and initialize the sample game, create a new `GameLiftClientSettings` asset. In the Unity editor main menu, choose **Assets, Create, Amazon GameLift, Client Settings**. If you create multiple copies of `GameLiftClientSettings` in your project, the plugin automatically detects this and notifies you which asset the plugin will update.

   1. In **Launch Game**, choose **Configure Client: Apply Managed EC2 Settings**. This action updates your game client settings to use the managed EC2 fleet that you just deployed.

1. Build your game client. Build a client executable using the standard Unity build process. In File, Build Settings, switch the platform to Windows, Mac, Linux. If you imported the sample game and initialized the settings, the build list and build target are automatically updated.

1. Launch the newly build game client executable. To start playing the game, start two to four client instances and use the UI in each to join a game session.

If you're using the sample game client, it has the following characteristics:
+ A player login component. When connecting to a game server on an Anywhere fleet, there is no player validation. You can enter any values to join the game session.
+ A simple join game UI. When a client attempts to join a game, the client automatically looks for an active game session with an available player slot. If no game session is available, the client requests a new game session. If a game session is available, the client requests to join the available game session. When testing your game with multiple concurrent clients, the first client starts the game session, and the remaining clients automatically join the existing game session.
+ Game sessions with four player slots. You can launch up to four game client instances concurrently and they will join the same game session. 

# Plugin for Unity: Deploy your game to a managed container fleet
Deploy to a managed container fleet

Use this guided plugin workflow to create a container image for your game server and deploy it to a container-based hosting solution. When you’ve successfully completed this workflow, your containerized game server is running in the cloud, and you can use the plugin to start a game client, connect to a game session, and play the game.

## Before you start


This workflow assumes that you’ve completed the following tasks. 
+ **Integrate your game server code with Amazon GameLift Servers server SDK.** our hosted game server must be able to communicate with the Amazon GameLift Servers service so that it can respond to requests to start new game sessions and report game session status. If you haven’t completed this task, we recommend that you follow the plugin workflow Host with Anywhere first. For guidance on preparing your game server code, see [Integrate your server code](unity-plug-in-anywhere.md#unity-plug-in-anywhere-integrate-server). For a managed container fleet, you must integrate your game with server SDK version 5.2 or higher.
**Note**  
If you imported the sample game, this task is already done for you. 
+ **Package your game server executable to run on Linux.** 
+ **Gather files to deploy with your game server build.** On your local machine, create a working directory to organize the files, which will be built into your game server container image. These might include game dependencies, a script to launch game servers and other processes when starting a container, etc. 
+ **Integrate your game client code with Amazon GameLift Servers.** One way to complete this task is to add a sample asset (included with the plugin) that’s already integrated. For guidance on preparing your game client code, see [Integrate your client code](unity-plug-in-anywhere.md#unity-plug-in-anywhere-integrate-client). 
+ **Install Docker on your local machine.** You need this tool installed if you want the plugin to create container images for you and push them to an ECR repository. Alternatively you can do these tasks manually and instruct the plugin to use an existing container image. For more information about building your image manually, see [ Build a container image for Amazon GameLift Servers](https://docs.aws.amazon.com/gameliftservers/latest/developerguide/containers-prepare-images.html).

**To start the Amazon GameLift Servers managed containers workflow:**
+ In the Unity editor main toolbar, choose the Amazon GameLift Servers menu, and select **Managed Containers**. This action opens the plugin page **Host with Managed Containers**, which presents a step-by-step process to create a container image with your game server build, deploy it to a container fleet, and launch your game. 

## Step 0: Set your profile


This section displays your currently selected user profile. Verify that the current user profile is the one you want to use for this workflow. All the resources that you create in this workflow are associated with the profile's AWS account and are placed in the profile's default AWS Region. The profile user's permissions determine your access to AWS resources and actions.

You might need to modify the selected user profile if: 
+ No profile is currently selected.
+ You want to select a different profile or create a new profile.
+ You need to bootstrap the selected profile (if bootstrap status is inactive).

**To set or change the selected user profile**
+ In the Amazon GameLift Servers menu, choose **Open AWS Access Credentials**.

## Step 1: Assess container readiness


Before deploying your game server to a container fleet, you must package it into a container image and store in an Amazon ECR repository. The plugin can complete these tasks for you or you can do these tasks manually. In this step, provide information about the status of your container image and the ECR repository. 

Use the assessment questions to tell the plugin what steps it needs to take: 
+ **Create a new container image.** If you choose this option, the next step will prompt you for the location of your game server build directory and the build executable. The plugin uses a Dockerfile template (supplied by Amazon GameLift Servers) and automatically configures it for your game. You can view the template at [Build a container image for Amazon GameLift Servers](containers-prepare-images.md). After choosing this option, indicate where you want the plugin to store the new image:
  + Create a new Amazon ECR repository and push the container image to it. The plugin creates a private ECR repo using the AWS account and default AWS Region in your selected user profile.
  + Push the container image to a previously created Amazon ECR repository. If you choose this option, the next step will prompt you to select an existing Amazon ECR repository from a list. The list includes all Amazon ECR repositories for the AWS account and default AWS Region in your selected user profile. You can select a public or private repository.
+ **Use an existing container image.** If you've manually built an image, we recommend that you use the Dockerfile template supplied by Amazon GameLift Servers, which is available at [Build a container image for Amazon GameLift Servers](containers-prepare-images.md). After choosing this option, indicate where the image is located. 
  + A locally stored Docker-generated image. If you choose this option, the plugin creates a new Amazon ECR private repository and pushes the local image file to it. The next step will prompt you for an image ID, which the plugin uses to locate the image file.
  + A container image that's already stored in an Amazon ECR repository. If you choose this option, the next step will prompt you to select an existing Amazon ECR repository and image from a list. The list includes all Amazon ECR repositories for the AWS account and default AWS Region in your selected user profile. You can select a public or private repository.
  +  Unity 6.3 on Linux requires glibc 2.35. Amazon Linux 2023 includes glibc 2.34. A Dockerfile template is provided below which handles building glibc 2.35 from source and configuring the Unity binaries to use glibc 2.35. 

### Dockerfile template for a Unity 6.3 game server container image


This template contains the minimum instructions that a game server container needs to usable in an Amazon GameLift Servers fleet. Modify the content as needed for your game server. 

```
# Base image
# ----------
  # Add the base image that you want to use over here,
  # Make sure to use an image with the same architecture as the
  # Instance type you are planning to use on your fleets.
FROM public.ecr.aws/amazonlinux/amazonlinux

# Game build directory
# --------------------
  # Add your game build directory in the 'GAME_BUILD_DIRECTORY' env variable below.
  #
# Game executable
# ---------------
  # Add the relative path to your executable in the 'GAME_EXECUTABLE' env variable below.
  # The game build provided over here needs to be integrated with gamelift server sdk.
  # This template assumes that the executable path is relative to the game build directory.
  #
# Launch parameters
# -----------------
  # Add any launch parameters to pass into your executable in the 'LAUNCH_PARAMS' env variable below.
  #
# Default directory
# -----------------
  # The value provided in 'HOME_DIR' below will be where the game executable and logs exist.
  #
ARG GAME_BUILD_DIRECTORY
ARG GAME_EXECUTABLE
ARG LAUNCH_PARAMS

ENV GAME_BUILD_DIRECTORY=$GAME_BUILD_DIRECTORY \
    GAME_EXECUTABLE=$GAME_EXECUTABLE \
    LAUNCH_PARAMS=$LAUNCH_PARAMS \
    HOME_DIR="/local/game"

# install dependencies as necessary
RUN yum install -y shadow-utils bison wget gcc make patchelf tar gzip && \
    yum clean all && rm -fr /var/cache

RUN mkdir -p $HOME_DIR
COPY .$GAME_BUILD_DIRECTORY/ $HOME_DIR

# Change directory to home
WORKDIR $HOME_DIR

# Build glibc 2.35 and patch Unity binaries
RUN GLIBC_VERSION="2.35" && \
    INSTALL_PREFIX="/opt/glibc-${GLIBC_VERSION}" && \
    ARCH=$(uname -m) && \
    if [ "$ARCH" = "x86_64" ]; then \
        INTERPRETER="${INSTALL_PREFIX}/lib/ld-linux-x86-64.so.2"; \
        MONO_ARCH="x86_64"; \
    elif [ "$ARCH" = "aarch64" ]; then \
        INTERPRETER="${INSTALL_PREFIX}/lib/ld-linux-aarch64.so.1"; \
        MONO_ARCH="aarch64"; \
    else \
        echo "ERROR: Unsupported architecture: $ARCH"; exit 1; \
    fi && \
    cd /tmp && \
    wget -q "https://ftp.gnu.org/gnu/glibc/glibc-${GLIBC_VERSION}.tar.gz" && \
    tar -xzf "glibc-${GLIBC_VERSION}.tar.gz" && \
    cd "glibc-${GLIBC_VERSION}" && mkdir glibc-build && cd glibc-build && \
    touch /etc/ld.so.conf && \
    ../configure --prefix="${INSTALL_PREFIX}" && \
    make -s all && make -s install && \
    cd / && rm -rf /tmp/glibc-* && \
    GLIBC_LIB="${INSTALL_PREFIX}/lib" && \
    EXECUTABLE_NAME=$(echo "$GAME_EXECUTABLE" | sed 's/\.[^.]*$//') && \
    DATA_DIR="$HOME_DIR/${EXECUTABLE_NAME}_Data" && \
    patchelf --set-interpreter "$INTERPRETER" "$HOME_DIR/$GAME_EXECUTABLE" && \
    patchelf --set-rpath "$GLIBC_LIB:$HOME_DIR:/lib64:$DATA_DIR/MonoBleedingEdge/$MONO_ARCH" "$HOME_DIR/$GAME_EXECUTABLE" && \
    patchelf --set-rpath "$GLIBC_LIB:/lib64" "$HOME_DIR/UnityPlayer.so" && \
    MONO_LIB="$DATA_DIR/MonoBleedingEdge/$MONO_ARCH/libmonobdwgc-2.0.so" && \
    if [ -f "$MONO_LIB" ]; then patchelf --set-rpath "$GLIBC_LIB:/lib64" "$MONO_LIB"; fi && \
    GAME_ASSEMBLY="$HOME_DIR/GameAssembly.so" && \
    if [ -f "$GAME_ASSEMBLY" ]; then patchelf --set-rpath "$GLIBC_LIB:/lib64" "$GAME_ASSEMBLY"; fi

RUN useradd -m gamescale && \
    echo "gamescale ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers && \
    chown -R gamescale:gamescale $HOME_DIR

# Add permissions to game build
RUN chmod +x ./$GAME_EXECUTABLE

USER gamescale

# Check directory before starting the container
RUN ls -lhrt .

# Check path before starting the container
RUN echo $PATH

# Start the game build
ENTRYPOINT ["/bin/sh", "-c", "./$GAME_EXECUTABLE $LAUNCH_PARAMS"]
```

## Step 2: Configure image deployment


In this step, provide information that the plugin needs to deploy your container image to a container fleet. This step requests the following information: 
+ The location of your game server build, container image, or Amazon ECR repository, based on your selections in Step 1. 
+ The scenario to use for your managed containers deployment.
+ Optional deployment settings. This section has configuration settings that the plugin uses by default. You can modify these or keep the default values
  + Game name is set to the name of your game project by default. All AWS resources that the plugin creates references the game name value.
  + Port range, memory limit, and vCPU limit are configuration settings for the container fleet. For more information about customizing these values, see [Configure network connections](containers-design-fleet.md#containers-custom-network) for connection port range, and [Set resource limits](containers-design-fleet.md#containers-design-fleet-limits) for resource limits.
  + Container image tag is used to categorize your container images in Amazon ECR. The default value is `unity-gamelift-plugin`.

### Deployment scenario options


#### Single-region container fleet


This scenario deploys your game server to a single container fleet. It's a good starting point for testing your server integration with AWS and your container configuration. It deploys the following resources. 
+ Amazon GameLift Servers container group definition describes how to deploy and run your container images on a container fleet. 
+ Amazon GameLift Servers container fleet (On-Demand) with your game server container installed and running, with alias.
+ Amazon Cognito user pool and client to enable players to authenticate and start a game.
+ API Gateway authorizer that links the user pool with APIs.
+ Web access control list (ACL) for throttling excessive player calls to API Gateway.
+ Backend service to make requests to the Amazon GameLift Servers service on behalf of game clients, such as to request game sessions and join games: 
  + API Gateway \$1 Lambda function for players to request a game session slot. This function calls `CreateGameSession()` if no open slots are available.
  + API Gateway \$1 Lambda function for players to get connection info for their game request.

#### Single-region container fleet with FlexMatch


This scenario deploys your game server to a container fleet, configures game session placement, and sets up FlexMatch matchmaking. This scenario is useful when you're ready to start designing a custom matchmaker for your hosting solution. Use this scenario to create the basic resources for this solution, which you can customize later as needed. It deploys the following resources:
+ Amazon GameLift Servers container group definition that describes how to deploy and run your container images on a container fleet. 
+ Amazon GameLift Servers container fleet (On-Demand) with your game server container installed and running, with alias.
+ FlexMatch matchmaking configuration and matchmaking rule set to accept player requests and form matches.
+ Amazon GameLift Servers game session queue that fulfills requests for proposed matches by finding the best possible hosting resource (based on viability, cost, player latency, etc.) and starting a game session.
+ Amazon Cognito user pool and client to enable players to authenticate and start a game.
+ API Gateway authorizer that links the user pool with APIs.
+ Web access control list (ACL) for throttling excessive player calls to API Gateway.
+ Backend service to make requests to the Amazon GameLift Servers service on behalf of game clients, such as to request game sessions and join games: 
  + API Gateway \$1 Lambda function for players to request a game session slot. This function calls `StartMatchmaking()` if no open slots are available.
  + API Gateway \$1 Lambda function for players to get connection info for their game request.
+ DynamoDB tables to store matchmaking tickets for players and game session information.
+ Amazon SNS topic \$1 Lambda function to handle GameSessionQueue events.

## Deploy container fleet


When your fleet configuration is complete, choose the **Deploy container fleet** button to start deployment. This process can take several minutes while the plugin creates a container image and pushes it to ECR, provisions hosting resources for the container fleet, deploys the fleet and other AWS resources for the selected hosting solution scenario. 

When you start a deployment, you can track the progress of each step. Depending on your configuration, the steps might include the following: 
+ Configuring container image
+ Creating an Amazon ECR repository 
+ Building an image and pushing to Amazon ECR
+ Creating container group definition
+ Creating container fleet

For more detailed deployment information, choose **View in AWS Management Console**. When the container fleet reaches active status, the fleet is actively running containers with server processes that are ready to host game sessions.

When deployment is complete, you have a working container fleet that’s ready to host game sessions and accept player connections. 

You can’t stop a deployment in progress. If the deployment enters a bad state or fails, you can start over by using the **Reset deployment** option.

## Launch client


At this point, you've completed all the tasks to launch and play your multiplayer game hosted with Amazon GameLift Servers. To play your game, choose **Start Client** to launch a local instance of your game client. 
+ If you deployed the single fleet scenario, open one instance of your game client with one player and enter the server map to move around. You can open a second instance of the game client to add a second player to the same server game map.
+ If you deployed the FlexMatch scenario, the hosting solution waits for at least two game clients to make matchmaking requests. Open at least two instances of your game client with one player. The two players will be matched and prompted to join a game session for the match. 

## Update a container fleet


If you've successfully deployed a managed containers hosting solution, you can use the **Update deployment**feature. This option lets you update configuration settings for a deployed container fleet, without having to create a new fleet. 

When updating a deployment, you can deploy a container image with a different game server build, change the Amazon ECR repository, choose a different deployment scenario, and customize optional configuration settings.

When you're ready to deploy your changes, choose Update. The time required for a deployment update is similar to a full deployment. For detailed deployment information, choose **View in AWS Management Console**.

## Clean up deployed resources


As a best practice, clean up the AWS resources for your managed containers solution as soon as you no longer need them. You might continue to incur costs for these resources if you don't remove them.

Delete the following resources:
+ Managed container resource stack. The resources in this stack depends on the deployment scenario you selected. To delete the entire stack, use the CloudFormation console. Stacks that are generated from the Amazon GameLift Servers plugin use the following naming convention: `GameLiftPluginForUnity-{GameName}-Containers`. Wait for the stack deletion process to complete before you initiate a new managed containers deployment in the plugin. For more information, see [ Delete a stack from the CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html).
+ Amazon ECR repository. If you used the plugin to create a repository for your container image, you might want to delete any repositories that are no longer needed. You don't need to delete a repository before resetting a managed containers deployment. If you update or reset a deployment, the plugin will automatically use the same repository unless directed to use another one. For more information, see [ Deleting a private repository in Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-delete.html).

# Amazon GameLift Servers plugin for Unity for server SDK 4
Plugin for Unity (server SDK 4)

**Note**  
This topic provides information for an earlier version of the Amazon GameLift Servers plugin for Unity. Version 1.x uses the server SDK for Amazon GameLift Servers 4.x or earlier. For documentation on the latest plugin version, which uses server SDK 5.x and supports newer features such as Amazon GameLift Servers Anywhere and managed container hosting, see [Amazon GameLift Servers plugin for Unity (server SDK 5.x)](unity-plug-in.md).

Amazon GameLift Servers provides tools for preparing your multiplayer game servers to run on Amazon GameLift Servers. The Amazon GameLift Servers plugin for Unity makes it easier to integrate Amazon GameLift Servers into your Unity game projects and deploy Amazon GameLift Servers resources for cloud hosting. Use the plugin for Unity to access Amazon GameLift Servers APIs and deploy AWS CloudFormation templates for common gaming scenarios.

After you've set up the plugin, you can try out the [Amazon GameLift Servers Unity sample](https://github.com/aws-samples/amazon-gamelift-unity) on GitHub.

**Topics**
+ [

# Integrate Amazon GameLift Servers with a Unity game server project
](integration-unity-server-sdk4.md)
+ [

# Integrate Amazon GameLift Servers with a Unity game client project
](integration-unity-client-sdk4.md)
+ [

## Install and set up the plugin
](#unity-plug-in-sdk4-install)
+ [

## Test your game locally
](#unity-plug-in-sdk4-test)
+ [

## Deploy a scenario
](#unity-plug-in-sdk4-scenario)
+ [

## Integrate games with Amazon GameLift Servers in Unity
](#unity-plug-in-sdk4-integration-intro)
+ [

## Import and run a sample game
](#unity-plug-in-sdk4-sample-game)

# Integrate Amazon GameLift Servers with a Unity game server project
Integrate a Unity game server

**Note**  
This topic provides information for an earlier version of the Amazon GameLift Servers plugin for Unity. Version 1.x uses the server SDK for Amazon GameLift Servers 4.x or earlier. For documentation on the latest plugin version, which uses server SDK 5.x and supports newer features such as Amazon GameLift Servers Anywhere and managed container hosting, see [Amazon GameLift Servers plugin for Unity (server SDK 5.x)](unity-plug-in.md).

This topic helps you prepare your custom game server for hosting on Amazon GameLift Servers. The game server must be able to notify Amazon GameLift Servers about its status, to start and stop game sessions when prompted, and to perform other tasks. For more information, see  [Add Amazon GameLift Servers to your game server with the server SDK](gamelift-sdk-server-api.md).

## Prerequisites


Before integrating your game server, complete the following tasks: 
+ [Set up an IAM service role for Amazon GameLift Servers](setting-up-role.md)
+ [Install and set up the plugin](unity-plug-in-sdk4.md#unity-plug-in-sdk4-install)

## Set up a new server process


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Set up communication with Amazon GameLift Servers and report that the server process is ready to host a game session. 

1. Initialize the server SDK by calling `InitSDK()`. 

1. To prepare the server to accept a game session, call `ProcessReady()` with the connection port and game session location details. Include the names of callback functions that Amazon GameLift Servers service invokes, such as `OnGameSession()`, `OnGameSessionUpdate()`, `OnProcessTerminate()`, `OnHealthCheck()`. Amazon GameLift Servers might take a few minutes to provide a callback.

1. Amazon GameLift Servers updates the status of the server process to `ACTIVE`.

1. Amazon GameLift Servers calls `onHealthCheck` periodically.

The following code example shows how to set up a simple server process with Amazon GameLift Servers. 

```
//initSDK
var initSDKOutcome = GameLiftServerAPI.InitSDK();
           
//processReady
// Set parameters and call ProcessReady
var processParams = new ProcessParameters(
    this.OnGameSession,
    this.OnProcessTerminate,
    this.OnHealthCheck,
    this.OnGameSessionUpdate,
    port,
    // Examples of log and error files written by the game server
    new LogParameters(new List<string>()          
        {
            "C:\\game\\logs",
            "C:\\game\\error"
        })
);
               
var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParams);
               
// Implement callback functions
void OnGameSession(GameSession gameSession)
{
    // game-specific tasks when starting a new game session, such as loading map
    // When ready to receive players
    var activateGameSessionOutcome = GameLiftServerAPI.ActivateGameSession();
}
               
void OnProcessTerminate()
{
    // game-specific tasks required to gracefully shut down a game session, 
    // such as notifying players, preserving game state data, and other cleanup
    var ProcessEndingOutcome = GameLiftServerAPI.ProcessEnding();
}
               
bool OnHealthCheck()
{
    bool isHealthy;
    // complete health evaluation within 60 seconds and set health
    return isHealthy;
}
```

## Start a game session


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

After game initialization is complete, you can start a game session.

1. Implement the callback function `onStartGameSession`. Amazon GameLift Servers invokes this method to start a new game session on the server process and receive player connections.

1. To activate a game session, call `ActivateGameSession()`. For more information about the SDK, see [C\$1 server SDK for Amazon GameLift Servers 4.x -- Actions](integration-server-sdk-csharp-ref-actions.md).

The following code example illustrates how to start a game session with Amazon GameLift Servers. 

```
void OnStartGameSession(GameSession gameSession)
{
    // game-specific tasks when starting a new game session, such as loading map   
    ...
    // When ready to receive players   
    var activateGameSessionOutcome = GameLiftServerAPI.ActivateGameSession();
}
```

## End a game session


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Notify Amazon GameLift Servers when a game session is ending. As a best practice, shut down server processes after game sessions complete to recycle and refresh hosting resources. 

1. Set up a function named `onProcessTerminate` to receive requests from Amazon GameLift Servers and call `ProcessEnding()`. 

1. The process status changes to `TERMINATED`.

The following example describes how to end a process for a game session.

```
var processEndingOutcome = GameLiftServerAPI.ProcessEnding();

if (processReadyOutcome.Success)
   Environment.Exit(0);

// otherwise, exit with error code
Environment.Exit(errorCode);
```

## Create server build and upload to Amazon GameLift Servers


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

After you integrate your game server with Amazon GameLift Servers, upload the build files to a fleet so that Amazon GameLift Servers can deploy it for game hosting. For more information on how to upload your server to Amazon GameLift Servers, see [Create a game server build for Amazon GameLift Servers](gamelift-build-cli-uploading.md).

# Integrate Amazon GameLift Servers with a Unity game client project
Integrate a Unity game client

**Note**  
This topic provides information for an earlier version of the Amazon GameLift Servers plugin for Unity. Version 1.x uses the server SDK for Amazon GameLift Servers 4.x or earlier. For documentation on the latest plugin version, which uses server SDK 5.x and supports newer features such as Amazon GameLift Servers Anywhere and managed container hosting, see [Amazon GameLift Servers plugin for Unity (server SDK 5.x)](unity-plug-in.md).

This topic helps you set up a game client to connect to Amazon GameLift Servers hosted game sessions through a backend service. Use Amazon GameLift Servers APIs to initiate matchmaking, request game session placement, and more. 

Add code to the backend service project to allow communication with the Amazon GameLift Servers service. A backend service handles all game client communication with the GameLift service. For more information about backend services, see .

 A backend server handles the following game client tasks: 
+ Customize authentication for your players. 
+ Request information about active game sessions from the Amazon GameLift Servers service.
+ Create a new game session.
+ Add a player to an existing game session.
+ Remove a player from an existing game session.

**Topics**
+ [

## Prerequisites
](#integration-unity-client-sdk4-prereq)
+ [

## Initialize a game client
](#integration-unity-client-sdk4-initialize)
+ [

## Create game session on a specific fleet
](#integration-unity-client-sdk4-game-session)
+ [

## Add players to game sessions
](#integration-unity-client-sdk4-add-player)
+ [

## Remove a player from a game session
](#integration-unity-client-sdk4-remove-player)

## Prerequisites


Before setting up game server communication with the Amazon GameLift Servers client, complete the following tasks: 
+ [Set up an AWS user account](setting-up-aws-login.md)
+ [Install and set up the plugin](unity-plug-in-sdk4.md#unity-plug-in-sdk4-install)
+ [Integrate Amazon GameLift Servers with a Unity game server project](integration-unity-server-sdk4.md)
+ [Deploy hosting fleets for Amazon GameLift Servers](fleets-intro.md)

## Initialize a game client


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Add code to initialize a game client. Run this code on launch, it's necessary for other Amazon GameLift Servers functions. 

1. Initialize `AmazonGameLiftClient`. Call `AmazonGameLiftClient` with either a default client configuration or a custom configuration. For more information on how to configure a client, see [Set up the Amazon GameLift Servers API](gamelift-sdk-client-api.md#gamelift-sdk-client-api-initialize). 

1. Generate a unique player id for each player to connect to a game session. For more information see [Generate player IDs](player-sessions-player-identifiers.md). 

   The following examples shows how to set up an Amazon GameLift Servers client. 

   ```
   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); 
           
       }
   }
   ```

## Create game session on a specific fleet


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Add code to start new game sessions on your deployed fleets and make them available to players. After Amazon GameLift Servers has created the new game session and returned a `GameSession`, you can add players to it. 
+ Place a request for a new game session. 
  + If your game uses fleets, call `CreateGameSession()` with a fleet or alias ID, a session name, and maximum number of concurrent players for the game.
  + If your game uses queues, call `StartGameSessionPlacement()`.

 The following example shows how to create a game session. 

```
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;
}
```

## Add players to game sessions


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

After Amazon GameLift Servers has created the new game session and returned a `GameSession` object, you can add players to it.

1. Reserve a player slot in a game session by creating a new player session. Use `CreatePlayerSession` or `CreatePlayerSessions` with the game session ID and a unique ID for each player.

1. Connect to the game session. Retrieve the `PlayerSession` object to get the game session's connection information. You can use this information to establish a direct connection to the server process: 

   1. Use the specified port and either the DNS name or IP address of the server process.

   1. Use the DNS name and port of your fleets. The DNS name and port are required if your fleets have TLS certificate generation enabled. 

   1. Reference the player session ID. The player session ID is required if your game server validates incoming player connections.

The following examples demonstrates how to reserve a player spot in a game session. 

```
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;  
}
```

The following code illustrates how to connect a player with the game session.

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

## Remove a player from a game session


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

You can remove the players from the game session when they leave the game.

1. Notify the Amazon GameLift Servers service that a player has disconnected from the server process. Call `RemovePlayerSession` with the player's session ID.

1. Verify that `RemovePlayerSession` returns `Success`. Then, Amazon GameLift Servers changes the player slot to be available, which Amazon GameLift Servers can assign to a new player. 

 The following example illustrates how to remove a player session. 

```
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());
    }
}
```

## Install and set up the plugin


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

This section describes how to download, install, and set up the Amazon GameLift Servers plugin for Unity, version 1.0.0. 

**Prerequisites**
+ Unity for Windows 2019.4 LTS, Windows 2020.3 LTS, or Unity for MacOS
+ Current version of Java
+ Current version of .NET 4.x

**To download and install the plugin for Unity**

1. Download the Amazon GameLift Servers plugin for Unity. You can find the latest version on the [Amazon GameLift Servers plugin for Unity repository](https://github.com/aws/amazon-gamelift-plugin-unity/releases) page. Under the [latest release](https://github.com/aws/amazon-gamelift-plugin-unity/releases), choose **Assets**, and then download the `com.amazonaws.gamelift-version.tgz` file. 

1. Launch Unity and choose a project.

1. In the top navigation bar, under **Window** choose **Package Manager**:  
![\[Unity menu under Window with package manager selected.\]](http://docs.aws.amazon.com/gameliftservers/latest/developerguide/images/unitypi_install_pkgmgr.png)

1. Under the **Package Manager** tab choose **\$1**, and then choose **Add package from tarball...**:  
![\[Add package from tarball highlighted under the + icon in the Package Manager tab.\]](http://docs.aws.amazon.com/gameliftservers/latest/developerguide/images/unitypi_install_tarball.png)

1. In the **Select packages on disk** window, navigate to the `com.amazonaws.gamelift` folder, choose the file `com.amazonaws.gamelift-version.tgz `, and then choose **Open**:  
![\[Choosing the tarball file in the select package on disk window.\]](http://docs.aws.amazon.com/gameliftservers/latest/developerguide/images/unitypi_install_tarballselect.png)

1. After Unity has loaded the plug-in, **Amazon GameLift Servers** appears as a new item in the Unity menu. It may take a few minutes to install and recompile scripts. The **Amazon GameLift Servers Plugin Settings** tab automatically opens.  
![\[Amazon GameLift Servers plugin for Unity plugin settings menu.\]](http://docs.aws.amazon.com/gameliftservers/latest/developerguide/images/unitypi_install_done_ui.png)

1. In the **SDK** pane, choose **Use .NET 4.x**.

   When configured, the status changes from **Not Configured** to **Configured**. 

## Test your game locally


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Use Amazon GameLift Servers Local to run Amazon GameLift Servers on your local device. You can use Amazon GameLift Servers Local to verify code changes in seconds, without a network connection.

### Configure local testing


1. In the plugin for Unity window, choose the **Test** tab.

1. In the **Test** pane, choose **Download Amazon GameLift Servers Local**. The plugin for Unity opens a browser window and downloads the `GameLift_06_03_2021.zip` file to your downloads folder.

   The download includes the C\$1 Server SDK, .NET source files, and a .NET component compatible with Unity.

1. Unzip the downloaded file `GameLift_06_03_2021.zip`. 

1. In the **Amazon GameLift Servers Plugin Settings** window, choose **Amazon GameLift Servers Local Path**, navigate to the unzipped folder, choose the file `GameLiftLocal.jar`, and then choose **Open**.

   When configured, local testing status changes from **Not Configured** to **Configured**.

1. Verify the status of the JRE. If the status is **Not Configured**, choose **Download JRE** and install the recommended Java version.

   After you install and configure the Java environment, the status changes to **Configured**.

### Run your local game


1. In the plugin for Unity tab, choose the **Test** tab.

1. In the **Test** pane, choose **Open Local Test UI**.

1. In the **Local Testing** window, specify a **Server executable path**. Select **...** to select the path and executable name of your server application.

1. In the **Local Testing** window, specify a **GL Local port**.

1. Choose **Deploy & Run** to deploy and run the server.

1. To stop your game server, choose **Stop** or close the game server windows.

## Deploy a scenario


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

A scenario uses an CloudFormation template to create the resources you need to deploy a cloud hosting solution for your game. This section describes the scenarios Amazon GameLift Servers provides and how to use them. 

**Prerequisites**  
To deploy the scenario, you need an IAM role for the Amazon GameLift Servers service. For information on how to create a role for Amazon GameLift Servers, see [Set up an AWS user account](setting-up-aws-login.md). 

Each scenario requires permissions to the following resources:
+ Amazon GameLift Servers
+ Amazon S3
+ CloudFormation
+ API Gateway
+ AWS Lambda
+ AWS WAFV2
+ Amazon Cognito

### Scenarios


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

The Amazon GameLift Servers Plug-in for Unity includes the following scenarios: 

**Auth only**  
This scenario creates a game backend service that performs player authentication without game server capability. The template creates the following resources in your account:
+ An Amazon Cognito user pool to store player authentication information.
+ An Amazon API Gateway REST endpoint-backed AWS Lambda handler that starts games and views game connection information.

**Single-Region fleet**  
This scenario creates a game backend service with a single Amazon GameLift Servers fleet. It creates the following resources: 
+ An Amazon Cognito user pool for a player to authenticate and start a game. 
+ An AWS Lambda handler to search for an existing game session with an open player slot on the fleet. If it can't find a open slot, it creates a new game session. 

**Multi-Region fleet with a queue and custom matchmaker**  
This scenario forms matches by using Amazon GameLift Servers queues and a custom matchmaker to group together the oldest players in the waiting pool. It creates the following resources:
+ An Amazon Simple Notification Service topic that Amazon GameLift Servers publishes messages to. For more information on SNS topics and notifications, see [Set up event notification for game session placement](queue-notification.md). 
+ A Lambda function that's invoked by the message that communicates placement and game connection details.
+ An Amazon DynamoDB table to store placement and game connection details. `GetGameConnection` calls read from this table and return the connection information to the game client. 

**Spot fleets with a queue and custom matchmaker**  
This scenario forms matches by using Amazon GameLift Servers queues and a custom matchmaker and configures three fleets. It creates the following resources:
+ Two Spot fleets that contain different instance types to provide durability for Spot unavailability.
+ An On-Demand fleet that acts as a backup for the other Spot fleets. For more information on designing your fleets, see [Hosting resource customizations](fleets-design.md).
+ An Amazon GameLift Servers queue to keep server availability high and cost low. For more information and best practices about queues, see [Customize a game session queue](queues-design.md). 

**FlexMatch**  
This scenario uses FlexMatch, a managed matchmaking service, to match game players together. For more information about FlexMatch, see [What is Amazon GameLift Servers FlexMatch](https://docs.aws.amazon.com/gameliftservers/latest/flexmatchguide/match-intro.html). This scenario creates the following resources:
+ A Lambda function to create a matchmaking ticket after it receives `StartGame` requests. 
+ A separate Lambda function to listen to FlexMatch match events.

To avoid unnecessary charges on your AWS account, remove the resources created by each scenario after you are done using them. Delete the corresponding CloudFormation stack. 

### Update AWS credentials


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

The Amazon GameLift Servers plugin for Unity requires security credentials to deploy a scenario. You can either create new credentials or use existing credentials.

For more information about configuring credentials, see [Understanding and getting your AWS credentials](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html). 

**To update AWS credentials**

1. In Unity, in the plugin for Unity tab, choose the **Deploy** tab.

1. In the **Deploy** pane, choose **AWS Credentials**.

1. You can create new AWS credentials or choose existing credentials. 
   + To create credentials, choose **Create new credentials profile**, and then specify the **New Profile Name**, **AWS Access Key ID**, **AWS Secret Key**, and **AWS Region**.
   + To choose existing credentials, choose **Choose existing credentials profile** and then select a profile name and **AWS Region**.

1. In the **Update AWS Credentials** window, choose **Update Credentials Profile**. 

### Update account bootstrap


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

The bootstrap location is an Amazon S3 bucket used during deployment. It's used to store game server assets and other dependencies. The AWS Region you choose for the bucket must be the same Region you will use for the scenario deployment.

For more information about Amazon S3 buckets, see [Creating, configuring, and working with Amazon Simple Storage Service buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-buckets-s3.html).

**To update the account bootstrap location**

1. In Unity, in the plugin for Unity tab, choose the **Deploy** tab.

1. In the **Deploy** pane, choose **Update Account Bootstrap**.

1. In the **Account Bootstrapping** window, you choose an existing Amazon S3 bucket or create a new Amazon S3 bucket:
   + To choose an existing bucket, choose **Choose existing Amazon S3 bucket** and **Update** to save your selection.
   + Choose **Create new Amazon S3 bucket** to create a new Amazon Simple Storage Service bucket, then choose a **Policy**. The policy specifies when the Amazon S3 bucket will be expire. Choose **Create** to create the bucket. 

### Deploy a game scenario


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

You can use a scenario to test your game with Amazon GameLift Servers. Each scenario uses a CloudFormation template to create a stack with the required resources. Most of the scenarios require a game server executable and build path. When you deploy the scenario, Amazon GameLift Servers copies game assets to the bootstrap location as part of deployment.

You must configure AWS credentials and an AWS account bootstrap to deploy a scenario.

**To deploy a scenario**

1. In Unity, in the plugin for Unity tab, choose the **Deploy** tab.

1. In the **Deploy** pane, choose **Open Deployment UI**.

1. In the **Deployment** window, choose a scenario.

1. Enter a **Game Name**. It must be unique. The game name is part of the CloudFormation stack name when you deploy the scenario. 

1. Choose the **Game Server Build Folder Path**. The build folder path points to the folder containing the server executable and dependencies.

1. Choose the **Game Server Build .exe File Path**. The build executable file path points to the game server executable.

1. Choose **Start Deployment** to begin deploying a scenario. You can follow the status of the update in the **Deployment** window under **Current State**.Scenarios can take several minutes to deploy.  
![\[Scenario deployment status update\]](http://docs.aws.amazon.com/gameliftservers/latest/developerguide/images/unitypi_deploy_statex.png)

1. When the scenario completes deployment, the **Current State** updates to include the **Cognito Client ID** and **API Gateway Endpoint** that you can copy and paste into the game.  
![\[Scenario deployment status update\]](http://docs.aws.amazon.com/gameliftservers/latest/developerguide/images/unitypi_deploy_statedone.png)

1. To update game settings, on the Unity menu, choose **Go To Client Connection Settings**. This displays an **Inspector** tab on the right side of the Unity screen.

1. Deselect **Local Testing Mode**.

1. Enter the **API Gateway Endpoint** and the **Coginito Client ID**. Choose the same AWS Region you used for the scenario deployment. You can then rebuild and run the game client using the deployed scenario resources. 

### Deleting resources created by the scenario


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

To delete the resources created for the scenario, delete the corresponding CloudFormation stack. 

**To delete resources created by the scenario**

1. In the Amazon GameLift Servers plugin for Unity **Deployment** window, select **View AWS CloudFormation Console** to open the CloudFormation console. 

1. In the CloudFormation console, choose **Stacks**, and then choose the stack that includes the game name specified during deployment.

1. Choose **Delete** to delete the stack. It may take a few minutes to delete a stack. After CloudFormation deletes the stack used by the scenario, its status changes to `ROLLBACK_COMPLETE`. 

## Integrate games with Amazon GameLift Servers in Unity


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Integrate your Unity game with Amazon GameLift Servers by completing the following tasks: 
+ [Integrate Amazon GameLift Servers with a Unity game server project](integration-unity-server-sdk4.md)
+ [Integrate Amazon GameLift Servers with a Unity game client project](integration-unity-client-sdk4.md)

The following diagram shows an example flow of integrating a game. In the diagram, a fleet with the game server is deployed to Amazon GameLift Servers. The game client communicates with the game server, which communicates with Amazon GameLift Servers. 

![\[Architecture diagram of integrating Unity with Amazon GameLift Servers.\]](http://docs.aws.amazon.com/gameliftservers/latest/developerguide/images/unity_diagram.png)


## Import and run a sample game


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

The Amazon GameLift Servers plugin for Unity includes a sample game you can use to explore the basics of integrating your game with Amazon GameLift Servers. In this section, you build the game client and game server and then test locally using Amazon GameLift Servers Local. 

### Prerequisites

+ [Set up an AWS user account](setting-up-aws-login.md)
+ [Install and set up the plugin](#unity-plug-in-sdk4-install)

### Build and run the sample game server


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Set up the game server files of the sample game.

1. In Unity, on the menu, choose **Amazon GameLift Servers**, and then choose **Import Sample Game**.

1. In the **Import Sample Game** window, choose **Import** to import the game, its assets and dependencies.

1. Build the game server. In Unity, on the menu, choose **Amazon GameLift Servers**, and then choose **Apply Windows Sample Server Build Settings** or **Apply MacOS Sample Server Build Settings**. After you configure the game server settings, Unity recompiles the assets. 

1. In Unity, on the menu, choose **File**, and then choose **Build**. Choose **Server Build**, choose **Build**, and then choose a build folder specifically for server files. 

   Unity builds the sample game server, placing the executable and required assets in the specified build folder.

### Build and run the sample game client


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Set up the game client files of the sample game.

1. In Unity, on the menu, choose **Amazon GameLift Servers**, and then choose **Apply Windows Sample Client Build Settings** or **Apply MacOS Sample Client Build Settings**. After the game client settings are configured, Unity will recompile assets. 

1. In Unity, on the menu, select **Go To Client Settings**. This will display an **Inspector** tab on the right side of the Unity screen. In the **Amazon GameLift Servers Client Settings** tab, select **Local Testing Mode**. 

1. Build the game client. In Unity, on the menu, choose **File**. Confirm **Server Build** is not checked, choose **Build**, and then select a build folder specifically for client files. 

   Unity builds the sample game client, placing the executable and required assets in the specified client build folder.

1. You've no built the game server and client. In the next steps, you run the game and see how it interacts with Amazon GameLift Servers.

### Test the sample game locally


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

Run the sample game you imported using Amazon GameLift Servers Local.

1. Launch the game server. In Unity, in the plugin for Unity tab, choose the **Deploy** tab.

1. In the **Test** pane, choose **Open Local Test UI**. 

1. In the **Local Testing** window, specify a **Game Server .exe File Path**. The path must include the executable name. For example, `C:/MyGame/GameServer/MyGameServer.exe`. 

1. Choose **Deploy and Run**. The plugin for Unity launches the game server and opens an Amazon GameLift Servers Local log window. The windows contains log messages including messages sent between the game server and Amazon GameLift Servers Local. 

1. Launch the game client. Find the build location with the sample game client and choose the executable file .

1. In the **Amazon GameLift Servers Sample Game**, provide an email and password and then choose **Log In**. The email and password aren't validated or used.

1. In the **Amazon GameLift Servers Sample Game**, choose **Start**. The game client looks for a game session. If it can't find a session, it creates one. The game client then starts the game session. You can see game activity in the logs.

#### Sample game server logs


```
...
2021-09-15T19:55:3495 PID:20728 Log :) GAMELIFT AWAKE 
2021-09-15T19:55:3512 PID:20728 Log :) I AM SERVER 
2021-09-15T19:55:3514 PID:20728 Log :) GAMELIFT StartServer at port 33430. 
2021-09-15T19:55:3514 PID:20728 Log :) SDK VERSION: 4.0.2 
2021-09-15T19:55:3556 PID:20728 Log :) SERVER IS IN A GAMELIFT FLEET 
2021-09-15T19:55:3577 PID:20728 Log :) PROCESSREADY SUCCESS. 
2021-09-15T19:55:3577 PID:20728 Log :) GAMELIFT HEALTH CHECK REQUESTED (HEALTHY)
...
2021-09-15T19:55:3634 PID:20728 Log :) GAMELOGIC AWAKE 
2021-09-15T19:55:3635 PID:20728 Log :) GAMELOGIC START 
2021-09-15T19:55:3636 PID:20728 Log :) LISTENING ON PORT 33430 
2021-09-15T19:55:3636 PID:20728 Log SERVER: Frame: 0 HELLO WORLD! 
...
2021-09-15T19:56:2464 PID:20728 Log :) GAMELIFT SESSION REQUESTED
2021-09-15T19:56:2468 PID:20728 Log :) GAME SESSION ACTIVATED
2021-09-15T19:56:3578 PID:20728 Log :) GAMELIFT HEALTH CHECK REQUESTED (HEALTHY)
2021-09-15T19:57:3584 PID:20728 Log :) GAMELIFT HEALTH CHECK REQUESTED (HEALTHY)
2021-09-15T19:58:0334 PID:20728 Log SERVER: Frame: 8695 Connection accepted: playerIdx 0 joined
2021-09-15T19:58:0335 PID:20728 Log SERVER: Frame: 8696 Connection accepted: playerIdx 1 joined 
2021-09-15T19:58:0338 PID:20728 Log SERVER: Frame: 8697 Msg rcvd from playerIdx 0 Msg: CONNECT: server IP localhost 
2021-09-15T19:58:0338 PID:20728 Log SERVER: Frame: 8697 Msg rcvd from player 0:CONNECT: server IP localhost 
2021-09-15T19:58:0339 PID:20728 Log SERVER: Frame: 8697 CONNECT: player index 0 
2021-09-15T19:58:0339 PID:20728 Log SERVER: Frame: 8697 Msg rcvd from playerIdx 1 Msg: CONNECT: server IP localhost 
2021-09-15T19:58:0339 PID:20728 Log SERVER: Frame: 8697 Msg rcvd from player 1:CONNECT: server IP localhost 
2021-09-15T19:58:0339 PID:20728 Log SERVER: Frame: 8697 CONNECT: player index 1
```

#### Sample Amazon GameLift Servers Local logs


```
12:55:26,000  INFO || - [SocketIOServer] main - Session store / pubsub factory used: MemoryStoreFactory (local session store only)
12:55:28,092  WARN || - [ServerBootstrap] main - Unknown channel option 'SO_LINGER' for channel '[id: 0xe23d0a14]'
12:55:28,101  INFO || - [SocketIOServer] nioEventLoopGroup-2-1 - SocketIO server started at port: 5757
12:55:28,101  INFO || - [SDKConnection] main - GameLift SDK server (communicates with your game server) has started on http://localhost:5757
12:55:28,120  INFO || - [SdkWebSocketServer] WebSocketSelector-20 - WebSocket Server started on address localhost/127.0.0.1:5759
12:55:28,166  INFO || - [StandAloneServer] main - GameLift Client server (listens for GameLift client APIs) has started on http://localhost:8080
12:55:28,179  INFO || - [StandAloneServer] main - GameLift server sdk http listener has started on http://localhost:5758
12:55:35,453  INFO || - [SdkWebSocketServer] WebSocketWorker-12 - onOpen socket: /?pID=20728&sdkVersion=4.0.2&sdkLanguage=CSharp and handshake /?pID=20728&sdkVersion=4.0.2&sdkLanguage=CSharp
12:55:35,551  INFO || - [HostProcessManager] WebSocketWorker-12 - client connected with pID 20728
12:55:35,718  INFO || - [GameLiftSdkHttpHandler] GameLiftSdkHttpHandler-thread-0 - GameLift API to use: ProcessReady for pId 20728
12:55:35,718  INFO || - [ProcessReadyHandler] GameLiftSdkHttpHandler-thread-0 - Received API call for processReady from 20728
12:55:35,738  INFO || - [ProcessReadyHandler] GameLiftSdkHttpHandler-thread-0 - onProcessReady data: port: 33430
 12:55:35,739  INFO || - [HostProcessManager] GameLiftSdkHttpHandler-thread-0 - Registered new process with pId 20728
12:55:35,789  INFO || - [GameLiftSdkHttpHandler] GameLiftSdkHttpHandler-thread-0 - GameLift API to use: ReportHealth for pId 20728
12:55:35,790  INFO || - [ReportHealthHandler] GameLiftSdkHttpHandler-thread-0 - Received API call for ReportHealth from 20728
12:55:35,794  INFO || - [ReportHealthHandler] GameLiftSdkHttpHandler-thread-0 - ReportHealth data: healthStatus: true
 12:56:24,098  INFO || - [GameLiftHttpHandler] Thread-12 - API to use: GameLift.DescribeGameSessions
12:56:24,119  INFO || - [DescribeGameSessionsDispatcher] Thread-12 - Received API call to describe game sessions with input: {"FleetId":"fleet-123"}
12:56:24,241  INFO || - [GameLiftHttpHandler] Thread-12 - API to use: GameLift.CreateGameSession
12:56:24,242  INFO || - [CreateGameSessionDispatcher] Thread-12 - Received API call to create game session with input: {"FleetId":"fleet-123","MaximumPlayerSessionCount":4}
12:56:24,265  INFO || - [HostProcessManager] Thread-12 - Reserved process: 20728 for gameSession: arn:aws:gamelift:local::gamesession/fleet-123/gsess-59f6cc44-4361-42f5-95b5-fdb5825c0f3d
12:56:24,266  INFO || - [WebSocketInvoker] Thread-12 - StartGameSessionRequest: gameSessionId=arn:aws:gamelift:local::gamesession/fleet-123/gsess-59f6cc44-4361-42f5-95b5-fdb5825c0f3d, fleetId=fleet-123, gameSessionName=null, maxPlayers=4, properties=[], ipAddress=127.0.0.1, port=33430, gameSessionData?=false, matchmakerData?=false, dnsName=localhost
12:56:24,564  INFO || - [CreateGameSessionDispatcher] Thread-12 - GameSession with id: arn:aws:gamelift:local::gamesession/fleet-123/gsess-59f6cc44-4361-42f5-95b5-fdb5825c0f3d created
12:56:24,585  INFO || - [GameLiftHttpHandler] Thread-12 - API to use: GameLift.DescribeGameSessions
12:56:24,585  INFO || - [DescribeGameSessionsDispatcher] Thread-12 - Received API call to describe game sessions with input: {"FleetId":"fleet-123"}
12:56:24,660  INFO || - [GameLiftSdkHttpHandler] GameLiftSdkHttpHandler-thread-0 - GameLift API to use: GameSessionActivate for pId 20728
12:56:24,661  INFO || - [GameSessionActivateHandler] GameLiftSdkHttpHandler-thread-0 - Received API call for GameSessionActivate from 20728
12:56:24,678  INFO || - [GameSessionActivateHandler] GameLiftSdkHttpHandler-thread-0 - GameSessionActivate data: gameSessionId: "arn:aws:gamelift:local::gamesession/fleet-123/gsess-59f6cc44-4361-42f5-95b5-fdb5825c0f3d"
```

### Shut down server process


**Note**  
This topic refers to Amazon GameLift Servers plugin for Unity version 1.0.0, which uses server SDK 4.x or earlier.

After you're done with your sample game, shut down the server in Unity.

1. In the game client, choose **Quit** or close the window to stop the game client. 

1. In Unity, in the **Local Testing** window, choose **Stop** or close the game server windows to stop the server. 