Call from Unity runtime
Invoke module endpoints from an authenticated game client in the Unity Editor.
Read time 4 minutesLast updated 18 hours ago
Run a module endpoint by calling it from an authenticated game client in the Unity Editor.
Prerequisites
To use Cloud Code in the Unity Editor, you must first install the Cloud Code SDK and link your Unity Gaming Services project to the Unity Editor.Link project
Link your Unity Gaming Services project with the Unity Editor. You can find your UGS project ID in the Unity Dashboard.- In Unity Editor, select Edit > Project Settings > Services.
-
Link your project.
-
If your project doesn't have a Unity project ID:
- Select Create a Unity Project ID > Organizations, then select an organization from the dropdown menu.
- Select Create project ID.
-
If you have an existing Unity project ID:
- Select Use an existing Unity project ID.
- Select an organization and a project from the dropdown menus.
- Select Link project ID.
-
If your project doesn't have a Unity project ID:
UnityEditor.CloudProjectSettings.projectIdSDK installation
To install the latest Cloud Code package for Unity Editor:- In the Unity Editor, open Window > Package Manager.
- In the Package Manager, select the Unity Registry list view.
- Search for , or locate the Cloud Code package in the list.
com.unity.services.cloudcode - Select the package, then click Install.
SDK setup
To get started with the Cloud Code SDK:- Ensure the service is enabled via the Cloud Code service dashboard page.
- Ensure that you have installed both the Cloud Code and the Authentication SDKs.
- Sign into your cloud project from within Unity Editor by selecting Edit > Project Settings... > Services.
- Create a new C# Monobehaviour script in Unity Editor. Refer to Creating and using scripts in the Unity Manual.
- In the script, initialize the Core SDK using await .
UnityServices.InitializeAsync() - In the script, initialize the Authentication SDK.
Typical workflow
You can call the Cloud Code SDK from a regular MonoBehaviour C# script within the Unity Editor.- Create a C# script within Unity Engine. Refer to Unity - Manual: Creating and Using Scripts.
MonoBehaviour - Within the script, configure the Unity Authentication service.
MonoBehaviour - Within the script, add a call to the Cloud Code SDK.
MonoBehaviour - Attach the script to a game object. Refer to Editor Scripting.
MonoBehaviour - Select Play and run the project to see Cloud Code in action.
Authentication
Players must have a valid player ID and access token to access the Cloud Code services. You must authenticate players with the Authentication SDK before using any of the Cloud Code APIs. You can do this by initializing the Authentication SDK inside a C# Monobehaviour script. Refer to Authenticate players. To initialize the Authentication SDK, include the following in your C# Monobehaviour script: C#To get started, we recommend using anonymous authentication. The following example demonstrates how to start anonymous authentication using the authentication package and log the player ID in a script within Unity Editor. C#await AuthenticationService.Instance.SignInAnonymouslyAsync();
using Unity.Services.Authentication;using System.Threading.Tasks;using Unity.Services.Core;using UnityEngine;public class AuthenticationExample : MonoBehaviour{ internal async Task Awake() { await UnityServices.InitializeAsync(); await SignInAnonymously(); } private async Task SignInAnonymously() { AuthenticationService.Instance.SignedIn += () => { var playerId = AuthenticationService.Instance.PlayerId; Debug.Log("Signed in as: " + playerId); }; AuthenticationService.Instance.SignInFailed += s => { // Take some action here... Debug.Log(s); }; await AuthenticationService.Instance.SignInAnonymouslyAsync(); }}
Calling a Cloud Code module endpoint
After including authentication in your newly created script, you are ready to call a Cloud Code module endpoint. Include the following namespace to integrate Cloud Code into your Unity Editor project:The samples below assume you have deployed a module calledUsing Unity.Services.CloudCode;
HelloWorldRollDiceusing System;using System.Threading.Tasks;using Unity.Services.CloudCode.Core;namespace HelloWorld;public class HelloWorld{ public class Response { public Response(int roll, int sides) { Roll = roll; Sides = sides; } public int Roll { get; set; } public int Sides { get; set; } } [CloudCodeFunction("RollDice")] public async Task<Response> RollDice(int diceSides) { var random = new Random(); var roll = random.Next(1, diceSides); return new Response(roll, diceSides); }}
Use editor bindings
You can generate editor bindings for your Cloud Code modules, so that you can use them in the Unity Editor interface. Refer to Generate bindings for more information. The following examples are a type-safe way to call your Cloud Code modules from the Unity Editor. Create a C# MonoBehaviour scriptRollDiceExampleusing Unity.Services.Authentication;using Unity.Services.CloudCode;using Unity.Services.CloudCode.GeneratedBindings;using Unity.Services.Core;using UnityEngine;public class RollDiceExample : MonoBehaviour{ private async void Start() { // Initialize the Unity Services Core SDK await UnityServices.InitializeAsync(); // Authenticate by logging into an anonymous account await AuthenticationService.Instance.SignInAnonymouslyAsync(); try { // Call the function within the module and provide the parameters we defined in there var module = new HelloWorldBindings(CloudCodeService.Instance); var result = await module.RollDice(6); Debug.Log($"You've rolled {result.Roll}/{result.Sides}"); } catch (CloudCodeException exception) { Debug.LogException(exception); } }}
Use CallModuleEndpointAsync
You can also use the CallModuleEndpointAsyncCallModuleEndpointAsyncCloudCodeService.Instance/// <summary>/// Calls a Cloud Code function./// </summary>/// <param name="module">Cloud Code Module to call</param>/// <param name="function">Cloud Code function to call.</param>/// <param name="args">Arguments for the cloud code function. Will be serialized to JSON.</param>/// <typeparam name="TResult">Serialized from JSON returned by Cloud Code.</typeparam>/// <returns>Serialized output from the called function.</returns>/// <exception cref="CloudCodeException">Thrown if request is unsuccessful.</exception>/// <exception cref="CloudCodeRateLimitedException">Thrown if the service returned rate limited error.</exception>Task<TResult> CallModuleEndpointAsync<TResult>(string module, string function, Dictionary<string, object> args = null);
- The parameter is the name of your module.
module - The parameter is the name of your module endpoint, which you labeled with the
functionattribute.CloudCodeFunction - The parameter is a dictionary of parameters to pass to the module endpoint.
args
RollDiceExampleusing System.Collections.Generic;using UnityEngine;using Unity.Services.Authentication;using Unity.Services.CloudCode;using Unity.Services.Core;public class RollDiceExample : MonoBehaviour{ // ResultType structure is the serialized response from the RollDice script in Cloud Code private class ResultType { public int Roll; public int Sides; } // Call this method public async void CallMethod() { await UnityServices.InitializeAsync(); // Sign in anonymously into the Authentication service if (!AuthenticationService.Instance.IsSignedIn) await AuthenticationService.Instance.SignInAnonymouslyAsync(); // Call out to the RollDice endpoint in the HelloWorld module in Cloud Code var response = await CloudCodeService.Instance.CallModuleEndpointAsync<ResultType>("HelloWorld", "RollDice", new Dictionary<string, object>( ) { { "diceSides", 6 } }); // Log the response of the module endpoint in console Debug.Log($"You rolled {response.Roll} / {response.Sides}"); }}
Run the script
To test the script, attach it to a game object in the Unity Editor, then select Play. You can include the following code in theStart()CallMethod()public void Start(){ CallMethod();}