Call from Unity Runtime

Run a script 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 your Unity Gaming Services project with the Unity Editor. You can find your UGS project ID in the Unity Cloud Dashboard.

  1. In Unity Editor, select Edit > Project Settings > Services.

  2. Link your project.

    • If your project doesn't have a Unity project ID:

      1. Select Create a Unity Project ID > Organizations, then select an organization from the dropdown menu.
      2. Select Create project ID.
    • If you have an existing Unity project ID:

      1. Select Use an existing Unity project ID.
      2. Select an organization and a project from the dropdown menus.
      3. Select Link project ID.

Your Unity Project ID appears, and the project is now linked to Unity services. You can also access your project ID in a Unity Editor script using UnityEditor.CloudProjectSettings.projectId.

SDK installation

To install the latest Cloud Code package for Unity Editor:

  1. In the Unity Editor, open Window > Package Manager.
  2. In the Package Manager, select the Unity Registry list view.
  3. Search for com.unity.services.cloudcode, or locate the Cloud Code package in the list.
  4. Select the package, then click Install.

Check Unity - Manual: Package Manager window to familiarize yourself with the Unity Package Manager interface.

SDK setup

The Cloud Code SDK can only call published scripts. Refer to Write scripts for more information on how to write and publish scripts.

To get started with the Cloud Code SDK:

  1. Ensure the service is enabled via the Cloud Code page in the Unity Cloud Dashboard page.
  2. Ensure that you have installed both the Cloud Code and the Authentication SDKs.
  3. Sign into your cloud project from within Unity Editor by selecting Edit > Project Settings... > Services.
  4. Create a new C# Monobehaviour script in Unity Editor. Refer to Creating and using scripts in the Unity Manual.
  5. In the script, initialize the Core SDK using await UnityServices.InitializeAsync().
  6. 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.

  1. Create a C# MonoBehaviour script within Unity Engine. Refer to Unity - Manual: Creating and Using Scripts.
  2. Within the MonoBehaviour script, configure the Unity Authentication service.
  3. Within the MonoBehaviour script, add a call to the Cloud Code SDK.
  4. Attach the MonoBehaviour script to a game object. Refer to Editor Scripting.
  5. 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](../authentication.md#Authenticate players).

To initialize the Authentication SDK, include the following in your C# Monobehaviour script:

C#

await AuthenticationService.Instance.SignInAnonymouslyAsync();

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#

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 script

After including authentication in your newly created script, you are ready to call a Cloud Code script. Include the following namespace to integrate Cloud Code into your Unity Editor project:

C#

Using Unity.Services.CloudCode;

To run a created script, use the CallEndpointAsync API client method, which you can find under CloudCodeService.Instance.

C#

/// <summary>
/// Calls a Cloud Code function.
/// </summary>
/// <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>
public async Task<TResult> CallEndpointAsync<TResult>(string function, Dictionary<string, object> args)

Note that the function parameter is the name of your script. To find the name of your script from the Unity Cloud Dashboard, open Cloud Code and select the Scripts tab.

Full integration example using C# Monobehaviour script

You can use the following code to publish a RollDice script with a diceSides integer parameter:

JavaScript

const _ = require("lodash-4.17");
module.exports = async ({ params, context, logger }) => {
  const roll = rollDice(params.diceSides);

  if (roll > params.diceSides) {
    // Log an error message with information about the exception
    logger.error("The roll is greater than the number of sides: " + roll);
    // Return an error back to the client
    throw Error("Unable to roll dice!");
  }
  return {
    sides: params.diceSides,
    roll: roll,
  };
};

function rollDice(sides) {
  return _.random(1, sides);
}

The following is a full example of how to integrate both the Authentication and Cloud Code services into your script:

C#

using 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 to roll the dice (use a button)
    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 Roll Dice script in Cloud Code
        var response = await CloudCodeService.Instance.CallEndpointAsync<ResultType>("RollDice", new Dictionary<string, object>( ) { { "diceSides", 6 } });

        // Log the response of the script in console
        Debug.Log($"You rolled {response.Roll} / {response.Sides}");
    }
}

To test the script, attach it to a game object in the Unity Editor, then select Play.

You can include the following code in the Start() method to call the CallMethod() method:

C#

public void Start()
    {
        CallMethod();
    }

You can serialize the response from the Cloud Code script into your preferred type. To learn more about the Cloud Code SDK, check Cloud Code SDK API.