ユースケースサンプル: 新規にサインアップしたプレイヤーのデフォルト設定値での初期化
Initialize new players with default values in Cloud Save when they first sign up.
読み終わるまでの所要時間 4 分最終更新 23日前
ユースケースサンプルは、Triggers を使用して、新しいプレイヤーが最初にサインアップしたときに Cloud Save のデフォルトの健全性とスタミナ値で初期化する方法を示します。Authentication サービス によって発行される
signedUp前提条件
最初に、必要なアクセスロールでサービスアカウントを作成し、UGS CLI を設定する必要があります。サービスアカウントを使用した認証
Triggers サービスを呼び出す前に、サービスアカウントを使用して認証する必要があります。- Unity Cloud Dashboard に移動します。
- Administration (管理) > Service Accounts (サービスアカウント) を選択します。
- New (新規) ボタンを選択し、サービスアカウントの名前と説明を入力します。
- Create (作成) を選択します。
- Manage product roles (製品ロールの管理) を選択します。
- 以下のロールをサービスアカウントに追加します。
- LiveOps ドロップダウンから、Triggers Configuration Editor (Triggers 設定編集者) および Triggers Configuration Viewer (Triggers 設定閲覧者) を選択します。
- Admin (管理者) ドロップダウンから Unity Environments Viewer (Unity 環境閲覧者) を選択します。
- LiveOps ドロップダウンから、Triggers Configuration Editor (Triggers 設定編集者) および Triggers Configuration Viewer (Triggers 設定閲覧者) を選択します。
- Save (保存) を選択します。
- Add Key (キーの追加) を選択します。
- base64 エンコードを使用して Key ID (キー ID) と Secret key (秘密鍵) をエンコードします。形式は "key_id:secret_key" です。この値をメモしておきます。
UGS CLI の設定
以下のステップに従って、UGS CLI の使用を準備します。- UGS CLI をインストール します。
-
プロジェクト ID と環境を以下のように設定します。
ugs config set project-id <your-project-id>
ugs config set environment-name <your-environment-name> - 前に作成したサービスアカウントを使用して認証します。認証の取得 を参照してください。
signed-up イベントを調べる
Authentication サービスは、プレイヤーが作成されたときにsigned-upイベントペイロードは、パラメーターとして Cloud Code に渡されます。 詳細については、認証: サインアップ を参照してください。{ "playerId": "string", "providerId": "string", "createdAt": "string"}
Cloud Code の設定
Cloud Save を呼び出すモジュールエンドポイントまたはスクリプトを定義して、新規に認証されたプレイヤーをデフォルトの健全性およびスタミナ値で初期化します。Cloud Code C# モジュール
以下のようなコンテンツで必須の文字列引数playerIdInitializeNewPlayerモジュールをデプロイします。 モジュールのデプロイ方法を学習するには、Hello World のデプロイ を参照してください。using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Shared;using Unity.Services.CloudSave.Model;public class ModuleSample{ private const string HealthKey = "HEALTH"; private const string StaminaKey = "STAMINA"; private const int DefaultValue = 100; private readonly ILogger<ModuleSample> _logger; public ModuleSample(ILogger<ModuleSample> logger) { _logger = logger; } [CloudCodeFunction("InitializeNewPlayer")] public async Task InitializeNewPlayer(IExecutionContext ctx, IGameApiClient gameApiClient, string playerId) { try { var response = await gameApiClient.CloudSaveData.GetItemsAsync(ctx, ctx.ServiceToken, ctx.ProjectId, playerId, new List<string>() { HealthKey, StaminaKey }); if (response.Data.Results.Count == 0) { await gameApiClient.CloudSaveData.SetItemBatchAsync(ctx, ctx.ServiceToken, ctx.ProjectId, playerId, new SetItemBatchBody(new List<SetItemBody>{new (HealthKey, DefaultValue), new (StaminaKey, DefaultValue)})); _logger.LogInformation("The player has been initialized with the {HealthKey} and {StaminaKey} keys with values of {DefaultValue}", HealthKey, StaminaKey, DefaultValue); } } catch (ApiException e) { _logger.LogError("Failed to initialize player data in Cloud Save. Error: {Error}", e.Message); throw new Exception($"Failed to initialize {playerId} data in Cloud Save. Error: {e.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
Cloud Code JavaScript スクリプト
以下の内容を使用して、必須の文字列パラメーターplayerIdInitializeNewPlayerJavaScript
const { DataApi } = require("@unity-services/cloud-save-1.4");const CLOUD_SAVE_HEALTH_KEY = "HEALTH";const CLOUD_SAVE_STAMINA_KEY = "STAMINA";const DEFAULT_VALUE = 100;module.exports = async ({ params, context, logger }) => { const cloudSaveApi = new DataApi(context); try { // Check if player has been initialized yet const cloudSaveGetResponse = await cloudSaveApi.getItems(context.projectId, params.playerId, [CLOUD_SAVE_HEALTH_KEY, CLOUD_SAVE_STAMINA_KEY]); if (cloudSaveGetResponse.data.results.length === 0) { // Record new values for player await cloudSaveApi.setItemBatch(context.projectId, params.playerId, { data: [ { key: CLOUD_SAVE_HEALTH_KEY, value: DEFAULT_VALUE, }, { key: CLOUD_SAVE_STAMINA_KEY, value: DEFAULT_VALUE, }, ], }); logger.info(`The player has been initialized with the ${CLOUD_SAVE_HEALTH_KEY} and ${CLOUD_SAVE_STAMINA_KEY} keys with values of ${DEFAULT_VALUE}`, { "affectedPlayerId": params.playerId }); return; } logger.info("The player has already been initialized.", { affectedPlayerId: params.playerId }); } catch (err) { logger.error("Failed to update Cloud Save data", { "error.message": err.message }, { "affectedPlayerId": params.playerId }); throw err; }};// Uncomment the code below to enable the inline parameter definition// - Requires Cloud Code JS dev environment setup with NodeJS (https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/manual/Authoring/javascript_project.html)//// module.exports.params = {// playerId: { type: "String", required: true },// };
スクリプトのデプロイ方法を学習するには、Hello World のデプロイ を参照してください。
トリガーの設定
Cloud Code リソースを Authenticationsigned-upnew-fileCloud Code スクリプトを作成した場合は、以下の設定でugs triggers new-file triggers-config
triggers-config.trCloud Code モジュールを作成した場合は、以下の設定で{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json", "Configs": [ { "Name": "initialize-new-player", "EventType": "com.unity.services.player-auth.signed-up.v1", "ActionUrn": "urn:ugs:cloud-code:InitializeNewPlayer", "ActionType": "cloud-code" } ]}
triggers-config.trUGS CLI ツールを使用して設定をデプロイします。{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json", "Configs": [ { "Name": "initialize-new-player", "EventType": "com.unity.services.player-auth.signed-up.v1", "ActionUrn": "urn:ugs:cloud-code:ModuleSample/InitializeNewPlayer", "ActionType": "cloud-code" } ]}
以下のようなレスポンスが返されます。ugs deploy triggers-config.tr
これで、プレイヤーがサインアップしたときに Cloud Code スクリプトまたはモジュールを実行するトリガーが設定されました。Deployed:triggers-config.tr
結果の検証
結果を検証するには、Authentication サービス を使用して新しいプレイヤーをサインアップします。これは、プレイヤーとして認証された任意の Unity Gaming Services のサービスを呼び出すことで行うことができます。 例えば、プレイヤー認証フローをトリガーするには、Unity Cloud Dashboard
signed-up- Unity Cloud Dashboard に移動します。
- Products (製品) > Player Management (プレイヤー管理) を選択します。
- リストからプレイヤーの 1 人を選択します。
- Cloud Save > Data (データ) タブに移動します。
- および
HEALTHキーが初期値のSTAMINAとともに表示されます。100