外部サービスとのインテグレーション
Cloud Code モジュールを外部サービスと統合できます。
カスタムデータ型を処理するには、カスタム JSON シリアル化 を実装します。
NuGet パッケージの使用
Cloud Code モジュールは .NET エコシステム内でライブになる C# ライブラリプロジェクトであるため、NuGet パッケージマネージャー を使用して依存関係をインストールします。これは、任意の外部 NuGet パッケージを Cloud Code モジュール内で使用できることを意味します。
使用可能な NuGet パッケージを表示するには、NuGet パッケージライブラリ を参照してください。
外部 API の呼び出し
任意の外部 API を呼び出すこともできます。以下のサンプルは、Cat Facts API を呼び出してランダムなネコの豆知識を取得します。
CatFactsApi
クラスを宣言して API 呼び出しを処理します。C#
using Newtonsoft.Json; using RestSharp; using Unity.Services.CloudCode.Core; using Unity.Services.CloudCode.Shared; namespace CatFacts; public interface ICatFactsApi { public Task<CatFactsApiResponse?> GetCatFact(); } public class CatFactsApiResponse { public string fact { get; set; } public int length { get; set; } } public class CatFactsApi : ICatFactsApi { private readonly RestClient _httpClient; public CatFactsApi() { // It's important to only create one RestClient per service in order to avoid creating and destroying too many network connections which could hurt performance _httpClient = new RestClient("https://catfact.ninja/fact"); } public async Task<CatFactsApiResponse?> GetCatFact() { var request = new RestRequest(); try { var res = await _httpClient.ExecuteGetAsync(request); return JsonConvert.DeserializeObject<CatFactsApiResponse?>(res.Content); } catch (ApiException e) { throw new Exception($"Failed to get cat fact: {e.Message}"); } } }
CatFactsApi
クラスをModuleConfig
クラス内のシングルトンとして宣言します。C#
public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi()); } }
CatFactsApi
クラスのGetCatFact
メソッドを呼び出すGetCatFact
関数を宣言します。C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Unity.Services.CloudCode.Core; using Unity.Services.CloudCode.Shared; namespace CatFacts; public class CatFactsSample { private static ILogger<CatFactsSample> _logger; public CatFactsSample(ILogger<CatFactsSample> logger) { _logger = logger; } [CloudCodeFunction("GetCatFact")] public async Task<CatFactsApiResponse?> GetCatFact(ICatFactsApi catFactsApi) { try { var fact = await catFactsApi.GetCatFact(); _logger.LogInformation("Cat fact: {fact}", fact?.fact); return fact; } catch (ApiException e) { _logger.LogError("Failed to get cat fact. Error: {Error}", e.Message); throw new Exception($"Failed to get cat fact: {e.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton<ICatFactsApi>(new CatFactsApi()); } } }
ゲームクライアントから
GetCatFact
関数を呼び出します。関数は、ランダムなネコの豆知識を返します。{ "output": { "fact": "The Amur leopard is one of the most endangered animals in the world.", "length": 68 } }
Unity サービスと統合する方法の詳細については、他の Unity サービスとのインテグレーション を参照してください。