

# Amazon GameLift Servers plugin for Unity (server SDK 5.x)
<a name="unity-plug-in"></a>

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
<a name="unity-plugin-install"></a>

**[ 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
<a name="unity-plug-in-profiles"></a>

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
<a name="unity-plug-in-profiles-bootstrap"></a>

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
<a name="unity-plug-in-anywhere"></a>

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
<a name="unity-plug-in-anywhere-profile"></a>

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
<a name="unity-plug-in-anywhere-integrate"></a>

**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
<a name="unity-plug-in-anywhere-integrate-server"></a>

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
<a name="unity-plug-in-anywhere-integrate-client"></a>

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
<a name="unity-plug-in-anywhere-fleet"></a>

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
<a name="unity-plug-in-anywhere-register"></a>

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
<a name="unity-plug-in-anywhere-launch"></a>

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
<a name="unity-plug-in-ec2"></a>

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
<a name="unity-plug-in-ec2-profile"></a>

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
<a name="unity-plug-in-ec2-integrate"></a>

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
<a name="unity-plug-in-ec2-integrate-server"></a>

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
<a name="unity-plug-in-ec2-integrate-client"></a>

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
<a name="unity-plug-in-ec2-integrate-install-script"></a>

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
<a name="unity-plug-in-ec2-scenarios"></a>

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
<a name="unity-plug-in-ec2-parameters"></a>

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
<a name="unity-plug-in-ec2-deploy"></a>

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
<a name="unity-plug-in-ec2-launch"></a>

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
<a name="unity-plug-in-container"></a>

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
<a name="unity-plug-in-container-prereqs"></a>

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
<a name="unity-plug-in-container-profile"></a>

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
<a name="unity-plug-in-container-assess"></a>

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
<a name="w2aab9c11b9c21c27c11c11b1"></a>

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
<a name="unity-plug-in-container-configure"></a>

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
<a name="unity-plug-in-container-configure-scenarios"></a>

#### Single-region container fleet
<a name="w2aab9c11b9c21c27c13b7b3b1"></a>

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
<a name="w2aab9c11b9c21c27c13b7b3b3"></a>

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
<a name="unity-plug-in-container-deploy"></a>

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
<a name="unity-plug-in-container-launch"></a>

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
<a name="unity-plug-in-container-update"></a>

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
<a name="unity-plug-in-container-cleanup"></a>

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).