Documentation

Development

User Acquisition

Monetization

Industry

Cloud Code

Scripting API

Services C# SDKs

Services JavaScript SDKs

Admin REST API

Client REST API

Scheduler Admin REST API

Observability REST API

Open Unity Dashboard

Cloud Code

LiveOps
​
​
Cloud Code
  • Overview
  • Get started
  • Server authority
  • Cloud Code C# modules
    • Overview
    • Get started
    • Concepts
    • Tutorials
      • Run modules
      • Write modules
      • Development essentials
      • Automate deployment
      • Integrate services
        • Integrate with other Unity Services
        • Interact with cross-player data
        • Integrate with external services
        • Use Access Control
        • Send push messages
      • Advanced configuration
      • Use Cases
    • Reference
  • Cloud Code JavaScript scripts
  • Logging
  • Use-case samples
  • Privacy and consent
  1. Cloud Code

Integrate with other Unity services

Integrate Cloud Code with various Unity Gaming Services using C# Software Development Kits or REST APIs.
Read time 9 minutes
Last updated 25 days ago

To unlock the full potential of Cloud Code, you can seamlessly integrate it with various Unity Gaming Services using either the C# Service SDKs or REST APIs.
The C# SDKs offer a simpler and more consistent experience, providing convenient access to Unity Gaming Services. If the Unity Gaming Service you wish to utilize already has a Cloud Code C# SDK, you can take advantage of it for a smoother integration. However, in cases where a specific UGS service lacks a Cloud Code C# SDK, you have the flexibility to connect with it directly through its REST API.
For some services where the state doesn't change frequently, such as Remote Config, it can be beneficial to introduce an in-memory cache to reduce the number of HTTP requests. For more information, refer to In-memory cache.

Connect to UGS through the UGS SDKs

To access the Cloud Code C# services SDK from NuGet, search for Com.Unity.Services.CloudCode.Apis. Once you install the package, you can use it within your C# modules to simplify the way you connect with other Unity services.
Note
The documentation for Cloud Code C# SDKs is incomplete. For more information, you can refer to the JavaScript documentation which has a similar structure. Please also make use of your IDE's auto complete and intellisense features.
For a full list of Cloud Code C# SDKs, refer to the Available Libraries page.

API Clients

The
GameApiClient
and
AdminApiClient
classes are both wrappers around the Cloud Code C# SDKs, providing simplified interfaces for calling Unity Gaming Services (UGS) from Cloud Code modules. However, they serve different purposes and are designed for distinct use cases.

Use the
GameApiClient
class

The
GameApiClient
class is specifically tailored for interacting with standard gaming services provided by UGS. It simplifies the process of calling UGS services from Cloud Code modules, such as reading and writing data in Cloud Save. You can use the class to access either Player Data, which is associated with an individual player, or Game Data, which is associated with the game as a whole and isn't tied to any one player. The examples below demonstrate both cases.
To use the
IGameApiClient
interface, register it as a singleton in your
ICloudCodeSetup
configurator:
using Unity.Services.CloudCode.Apis.Extensions;using Unity.Services.CloudCode.Core;public class ModuleConfig : ICloudCodeSetup{ public void Setup(ICloudCodeConfig config) { config.AddGameApiClient(); }}
Note
In the
Unity.Services.CloudCode.Apis.Extensions
namespace,
config.AddGameApiClient()
is available from
com.unity.services.cloudcode.core
version 0.0.4 and
com.unity.services.cloudcode.apis
version 0.0.24.
In earlier versions, do the following to register the client manually:
config.Dependencies.AddSingleton<IGameApiClient>(GameApiClient.Create());

Save and retrieve Player Data

You can use the
IGameApiClient
interface in any function that you attribute with
CloudCodeFunction
. To use the
IGameApiClient
interface, pass it as a parameter to the function.
The following example demonstrates how to save and read Player Data from Cloud Save. Player Data is tied to
context.PlayerId
and authenticated with
context.AccessToken
:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Apis.Extensions;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;using Unity.Services.CloudSave.Model;namespace ExampleModule;public class CloudSaveSdkSample{ private readonly ILogger<CloudSaveSdkSample> _logger; public CloudSaveSdkSample(ILogger<CloudSaveSdkSample> logger) { _logger = logger; } [CloudCodeFunction("SavePlayerData")] public async Task SavePlayerData(IExecutionContext context, IGameApiClient gameApiClient, string key, string value) { try { await gameApiClient.CloudSaveData.SetItemAsync( context, context.AccessToken!, context.ProjectId!, context.PlayerId!, new SetItemBody(key, value)); _logger.LogInformation("Successfully saved data for key: {Key}", key); } catch (ApiException ex) { _logger.LogError("Failed to save data for key {Key}. Error: {Error}", key, ex.Message); throw new Exception($"Unable to save player data: {ex.Message}"); } } [CloudCodeFunction("GetPlayerData")] public async Task<string> GetPlayerData(IExecutionContext context, IGameApiClient gameApiClient, string key) { try { var result = await gameApiClient.CloudSaveData.GetItemsAsync( context, context.AccessToken!, context.ProjectId!, context.PlayerId!, new List<string> { key }); var data = result.Data.Results.FirstOrDefault()?.Value?.ToString() ?? string.Empty; _logger.LogInformation("Successfully retrieved data for key: {Key}", key); return data; } catch (ApiException ex) { _logger.LogError("Failed to retrieve data for key {Key}. Error: {Error}", key, ex.Message); throw new Exception($"Unable to retrieve player data: {ex.Message}"); } }}public class ModuleConfig : ICloudCodeSetup{ public void Setup(ICloudCodeConfig config) { config.AddGameApiClient(); }}

Save and retrieve Game Data

The following example demonstrates how to save and read Game Data from Cloud Save. Unlike Player Data, Game Data isn't tied to
context.PlayerId
. Instead, you provide your own identifier (
customId
) for the non-player entity you want to associate the data with, such as a guild or a piece of global game state, and authenticate with
context.ServiceToken
instead of
context.AccessToken
. For more information on Game Data, refer to Cloud Save Game Data. For more information on when to use the
ServiceToken
, refer to Service and access token support.
Important
This example authenticates with
context.ServiceToken
, which grants cross-player access to non-player data. Because
customId
is accepted directly from the caller, any player who can invoke this function could pass a different
customId
to read or write another guild's or another game-wide record. Don't expose a
ServiceToken
-authenticated function to unrestricted player access. Restrict the module endpoint with Access Control rules, or validate
customId
against the calling player's own permissions before you use it.
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Apis.Extensions;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;using Unity.Services.CloudSave.Model;namespace ExampleModule;public class CloudSaveGameDataSample{ private readonly ILogger<CloudSaveGameDataSample> _logger; public CloudSaveGameDataSample(ILogger<CloudSaveGameDataSample> logger) { _logger = logger; } [CloudCodeFunction("SaveGameData")] public async Task SaveGameData(IExecutionContext context, IGameApiClient gameApiClient, string customId, string key, string value) { try { await gameApiClient.CloudSaveData.SetCustomItemAsync( context, context.ServiceToken, context.ProjectId!, customId, new SetItemBody(key, value)); _logger.LogInformation("Successfully saved game data for key: {Key}", key); } catch (ApiException ex) { _logger.LogError("Failed to save game data for key {Key}. Error: {Error}", key, ex.Message); throw new Exception($"Unable to save game data: {ex.Message}"); } } [CloudCodeFunction("GetGameData")] public async Task<string> GetGameData(IExecutionContext context, IGameApiClient gameApiClient, string customId, string key) { try { var result = await gameApiClient.CloudSaveData.GetCustomItemsAsync( context, context.ServiceToken, context.ProjectId!, customId, new List<string> { key }); var data = result.Data.Results.FirstOrDefault()?.Value?.ToString() ?? string.Empty; _logger.LogInformation("Successfully retrieved game data for key: {Key}", key); return data; } catch (ApiException ex) { _logger.LogError("Failed to retrieve game data for key {Key}. Error: {Error}", key, ex.Message); throw new Exception($"Unable to retrieve game data: {ex.Message}"); } }}public class ModuleConfig : ICloudCodeSetup{ public void Setup(ICloudCodeConfig config) { config.AddGameApiClient(); }}
For an example of these functions called from a Unity client, including saving and then loading the data, refer to Save and load data.

Use the
AdminApiClient
class

The
AdminApiClient
class is intended for accessing administrative functionalities of UGS services. It provides a simplified interface for calling UGS admin-related services from Cloud Code modules. The example illustrates how to create a leaderboard using the AdminApiClient, showcasing its utility for administrative tasks.
Note
The Admin APIs have lower rate limits than the Game APIs. Use the Admin APIs for administrative tasks only. Don't use them for player-scale operations. Use the Game APIs to achieve all functionality intended for player-scale operations. Refer to Limits.
To use the
IAdminApiClient
interface, register it as a singleton in your
ICloudCodeSetup
configurator:
using Unity.Services.CloudCode.Apis.Extensions;using Unity.Services.CloudCode.Core;public class ModuleConfig : ICloudCodeSetup{ public void Setup(ICloudCodeConfig config) { config.AddAdminApiClient(); }}
Note
In the
Unity.Services.CloudCode.Apis.Extensions
namespace,
config.AddAdminApiClient()
is available from
com.unity.services.cloudcode.apis
version 0.0.27.
In earlier versions, do the following to register the client manually:
config.Dependencies.AddSingleton<IAdminApiClient>(AdminApiClient.Create());

Usage Example

Similar to the
IGameApiClient
, the
IAdminApiClient
interface can be employed in any function attributed with
CloudCodeFunction
. When using the
IAdminApiClient
interface, pass it as a parameter to the function.
Note
To use admin functionality with the admin SDK, you need valid service account credentials with the
Leaderboards Admin
Project role. To create a service account, please refer to Admin authentication.
Important
This Cloud Code example demonstrates the use of hardcoded plaintext service account credentials. Use caution when you handle credentials and code with secrets. To ensure security, it is recommended that you don’t commit secrets to version control. If your credentials become compromised, you can regenerate your service account credentials immediately. A more secure method to store credentials in Cloud Code is in development.
The following example demonstrates how to create a Leaderboard:
using System;using System.Threading.Tasks;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Apis.Admin;using Unity.Services.CloudCode.Apis.Extensions;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;using Unity.Services.Leaderboards.Admin.Model;namespace ExampleModule;public class ModuleMain{ private static ILogger<ModuleMain> _logger; public ModuleMain(ILogger<ModuleMain> logger) { _logger = logger; } [CloudCodeFunction("CreateLeaderboard")] public async Task CreateLeaderboard(IExecutionContext context, IAdminApiClient adminApiClient) { try { await adminApiClient.Leaderboards.CreateLeaderboardAsync( executionContext: context, serviceAccountKey: "YOUR_SERVICE_ACCOUNT_KEY", serviceAccountSecret: "YOUR_SERVICE_ACCOUNT_SECRET", projectId: Guid.Parse(context.ProjectId), environmentId: Guid.Parse(context.EnvironmentId), leaderboardIdConfig: new LeaderboardIdConfig( id: "new-leaderboard", name: "new-leaderboard", sortOrder: SortOrder.Asc, updateType: UpdateType.KeepBest ) ); } catch (ApiException ex) { _logger.LogError("Failed to create a Leaderboard. Error: {Error}", ex.Message); throw new Exception($"Failed to create a Leaderboard. Error: {ex.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.AddAdminApiClient(); } }}

Connect to UGS through REST APIs

If you want to use a service that doesn't have a C# SDK yet, you can also connect with the services directly through their REST API.

Authentication

Depending on your use case, you can use either the
AccessToken
or the
ServiceToken
to authenticate the API call. If you use the
ServiceToken
to authenticate UGS Client APIs, ensure the service you want to call supports service tokens. For a list of services and use cases that support service tokens, refer to the Service and access token support documentation.
Note
If the service you want to call provides a Cloud Code C# SDK, you can use the SDK instead of calling the service API directly. For more information, refer to the list of Available libraries.

Calling the API

Dependency Injection allows you to create API interfaces as singletons and inject them into your modules.
Note
In addition to UGS APIs, you can also implement external APIs as singletons. For an example of how to implement an external API, refer to the documentation on how to integrate with external services.

Copyright © 2026 Unity Technologies
LegalPrivacy PolicyCookiesDocumentation Terms of UseDo Not Sell or Share My Personal InformationYour Privacy Choices (Cookie Settings)

"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S and elsewhere (more info here). Other names or brands are trademarks of their respective owners.

Some pages are machine-translated for convenience, and may contain inaccuracies. In the event of conflicting information, the English version is authoritative.

  • On this page
    • Connect to UGS through the UGS SDKs

      • API Clients

      • Use the GameApiClient class

        • Save and retrieve Player Data

        • Save and retrieve Game Data

      • Use the AdminApiClient class

        • Usage Example

    • Connect to UGS through REST APIs

      • Authentication

      • Calling the API


Report a problem with this page
​
​