从 Unity Runtime 调用
在 Unity 编辑器中从经过身份验证的游戏客户端调用脚本来运行该脚本。
先决条件
要在 Unity 编辑器中使用 Cloud Code,必须先安装 Cloud Code SDK,并将 Unity Gaming Services(Unity 游戏服务)项目关联到 Unity 编辑器。
关联项目
将 Unity Gaming Services(Unity 游戏服务)项目与 Unity 编辑器关联。您可以在 Unity Cloud Dashboard 中找到您的 UGS Project ID。
在 Unity 编辑器中,选择 Edit(编辑)> Project Settings(项目设置)> Services(服务)。
关联您的项目。
如果项目没有 Unity Project ID:
- 选择 Create a Unity Project ID(创建 Unity Project ID)> Organizations(组织),然后从下拉菜单中选择一个组织。
- 选择 Create project ID(创建 Project ID)。
如果已有 Unity Project ID:
- 选择 Use an existing Unity project ID(使用现有 Unity Project ID)。
- 从下拉菜单中选择组织和项目。
- 选择 Link project ID(关联 Project ID)。
此时将显示您的 Unity Project ID,并且项目现在已关联到 Unity 服务。此外,还可以使用 UnityEditor.CloudProjectSettings.projectId
在 Unity 编辑器脚本中访问您的 Project ID。
SDK 安装
要安装适用于 Unity 编辑器的最新 Cloud Code 包,请执行以下操作:
- 在 Unity 编辑器中,打开 Window(窗口)> Package Manager(包管理器)。
- 在 Package Manager(包管理器)中,选择 **Unity Registry(Unity 注册表)**列表视图。
- 搜索
com.unity.services.cloudcode
或在列表中找到 Cloud Code 包。 - 选择包,然后单击 Install(安装)。
请查看 Unity - 手册:Package Manager(包管理器)窗口,熟悉 Unity Package Manager(包管理器)界面。
SDK 设置
Cloud Code SDK 只能调用已发布的脚本。如需更多有关如何编写和发布脚本的信息,请参阅编写脚本。
开始使用 Cloud Code SDK:
- 确保在 Unity Cloud Dashboard 中通过 Cloud Code 页面启用该服务。
- 确保 Cloud Code SDK 和 Authentication SDK 均已安装。
- 在 Unity 编辑器中选择 Edit(编辑)> Project Settings...(项目设置...)> **Services(服务)**登录到您的云项目。
- 在 Unity 编辑器中创建新的 C# Monobehaviour 脚本。请参阅 Unity 手册中的创建和使用脚本。
- 在脚本中,使用 await
UnityServices.InitializeAsync()
初始化 Core SDK。 - 在脚本中,初始化 Authentication SDK。
典型工作流程
您可以在 Unity 编辑器中从常规 MonoBehaviour C# 脚本调用 Cloud Code SDK。
- 在 Unity 引擎中创建 C#
MonoBehaviour
脚本。请参阅 Unity - 手册:创建和使用脚本。 - 在
MonoBehaviour
脚本中,配置 Unity Authentication 服务。 - 在
MonoBehaviour
脚本中,添加对 Cloud Code SDK 的调用。 - 将
MonoBehaviour
脚本附加到游戏对象。请参阅编辑器脚本。 - 选择 **Play(运行)**并运行项目,查看 Cloud Code 的运行情况。
身份验证
玩家必须拥有有效的玩家 ID 和访问令牌才能访问 Cloud Code 服务。在使用任何 Cloud Code API 之前,您必须使用 Authentication SDK 对玩家进行身份验证。为此,可以在 C# Monobehaviour 脚本中初始化 Authentication SDK。请参阅[对玩家进行身份验证](../authentication.md#Authenticate players)。
要初始化 Authentication SDK,请在 C# Monobehaviour 脚本中添加以下代码:
C#
await AuthenticationService.Instance.SignInAnonymouslyAsync();
首先,我们建议使用匿名身份验证。以下示例演示了如何使用身份验证包启动匿名身份验证,并在 Unity 编辑器中使用脚本记录玩家 ID。
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();
}
}
调用 Cloud Code 脚本
在新创建的脚本中加入身份验证后,您就可以调用 Cloud Code 脚本了。为了将 Cloud Code 集成到 Unity 编辑器项目中,请添加以下命名空间:
C#
Using Unity.Services.CloudCode;
要运行创建的脚本,请使用 CallEndpointAsync
API 客户端方法。该方法可在 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)
请注意,function
参数是脚本的名称。要从 Unity Cloud Dashboard 中查找脚本的名称,请打开 Cloud Code 并选择 **Scripts(脚本)**选项卡。
使用 C# Monobehaviour 脚本的完整集成示例
您可以使用以下代码发布带有 diceSides
整数参数的 RollDice
脚本:
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);
}
以下是如何将 Authentication 和 Cloud Code 服务集成到脚本中的完整示例:
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}");
}
}
要测试该脚本,请将其附加到 Unity 编辑器中的游戏对象,然后选择 Play(运行)。
您可以在 Start()
方法中包含以下代码来调用 CallMethod()
方法:
C#
public void Start()
{
CallMethod();
}
您可以将 Cloud Code 脚本的响应序列化为偏好的类型。要了解有关 Cloud Code SDK 的更多信息,请查看 Cloud Code SDK API。