数据传输对象 (DTO)
您可以在模块中定义数据传输对象。这些对象用于在客户端和服务器之间传输数据。如果要将模块数据序列化为 JSON,并在客户端将其反序列化为相同的结构,则可以使用 DTO。
先决条件
在开始使用 DTO 之前,请创建一个 Cloud Code 模块。
管理 DTO
您可以定义 DTO 来捕获模块终端函数的数据类型。
创建和配置 DTO 项目
首先,请创建一个 C# 项目来存储 DTO,并在主项目中添加对该项目的引用。请参阅管理项目中的引用 (Microsoft)。
请参阅模块结构以了解更多信息。
接下来,必须将 DTO C# 项目配置为在 Unity 编辑器中使用受支持的运行时 .NET 版本,即 netstandard
。
打开 <project_name>.csproj
文件,然后更改 TargetFramework
。如果使用的是 Unity 2021.2.0,则设置为 netstandard.2.1
。请参阅支持的 .NET 版本(Unity 手册)以了解更多信息。您还需要禁用隐式使用。请参阅下面的 C# 项目配置示例:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>DTOSample</RootNamespace>
</PropertyGroup>
</Project>
将 DTO 添加到模块
在项目中定义一个新类来存储 DTO。这个类可以如下所示:
namespace DTOSample
{
public class DiceRollDto
{
public DiceRollDto(int roll, int sides)
{
Roll = roll;
Sides = sides;
}
public int Roll { get; set; }
public int Sides { get; set; }
}
}
在模块逻辑中使用 DTO
在包含模块函数的主项目中,定义游戏逻辑,并使用定义的 DTO 作为函数返回类型。
下面是简单模块终端的一个示例:
using DTOSample;
using Unity.Services.CloudCode.Core;
namespace Sample;
public class HelloWorld
{
[CloudCodeFunction("RollDice")]
public async Task<DiceRollDTO> RollDice(int diceSides)
{
var random = new Random();
var roll = random.Next(1, diceSides);
return new DiceRollDTO(roll, diceSides);
}
}
注意:还可以使用 DTO 作为函数参数进行输入。
提取 DLL
为了在 Unity 项目中使用 DTO 来匹配响应类型,需要从模块 C# 项目中提取 DLL。应为此步骤部署模块,以便以后能够调用模块函数。
假设已在部署模块时生成了程序集,默认情况下,您可以在模块项目的 bin/Debug/Release/net6.0/linux-x64/publish
文件夹中找到 DLL。
程序集可能如下所示:
├─ Main.csproj
└─ bin
└─ Debug
└─ Release
└─ net6.0
└─ linux-x64
└─ publish
└─ Main.dll
└─ Main.pdb
└─ DTOs.dll
└─ DTOs.pdb
...
复制 DTOs.dll
文件。
如需更多有关如何生成程序集的信息,请参阅打包代码。
将 DLL 导入 Unity 项目
要在游戏中使用外部 DLL,只需将其放在 Unity 项目的 Assets
目录中即可。Unity 编辑器下次在同步项目时将添加必要的 DLL 引用。
请参阅托管插件(Unity 手册)以了解更多信息。
在 Unity MonoBehaviour 脚本中重用 DTO
您可以随后调用 Cloud Code SDK,并使用相同的 DTO 对响应进行反序列化:
using DTOSample;
using UnityEngine;
using Unity.Services.Authentication;
using Unity.Services.CloudCode;
using Unity.Services.Core;
public class Test : MonoBehaviour
{
// Call this method to roll the dice (use a button)
public async void Awake()
{
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.CallModuleEndpointAsync<DiceRollDto>("Main", "RollDice", new Dictionary<string, object>()
{
{"diceSides", 6}
});
// Log the response of the script in console
Debug.Log($"You rolled {response.Roll} / {response.Sides}");
}
}
成功的响应如下所示:
"You rolled 5 / 6"
请参阅从 Unity Runtime 运行模块以了解更多信息。