ユースケースサンプル: スコアが破られたプレイヤーにプッシュメッセージを送信する
Send a push message to a player whose leaderboard score was beaten by another player.
読み終わるまでの所要時間 5 分最終更新 23日前
このユースケースサンプルは、Triggers を使用して、リーダーボード内のスコアが破られたプレイヤーにプッシュメッセージを送信する方法を示します。サンプルでは、Leaderboards サービス から
score-submitted前提条件
最初に、必要なアクセスロールでサービスアカウントを作成し、UGS CLI を設定する必要があります。サービスアカウントを使用した認証
Triggers サービスを呼び出す前に、サービスアカウントを使用して認証する必要があります。- Unity Cloud Dashboard に移動します。
- Administration (管理) > Service Accounts (サービスアカウント) を選択します。
- New (新規) ボタンを選択し、サービスアカウントの名前と説明を入力します。
- Create (作成) を選択します。
- Manage product roles (製品ロールの管理) を選択します。
- 以下のロールをサービスアカウントに追加します。
- LiveOps ドロップダウンから、Triggers Configuration Editor (Triggers 設定編集者)、Triggers Configuration Viewer (Triggers 設定閲覧者)、Leaderboards Admin (Leaderboards 管理者) を選択します。
- Admin (管理者) ドロップダウンから Unity Environments Viewer (Unity 環境閲覧者) を選択します。
- LiveOps ドロップダウンから、Triggers Configuration Editor (Triggers 設定編集者)、Triggers Configuration Viewer (Triggers 設定閲覧者)、Leaderboards Admin (Leaderboards 管理者) を選択します。
- 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> - 前に作成したサービスアカウントを使用して認証します。認証の取得 を参照してください。
Leaderboards の設定
このサンプルに従うには、リーダーボードを作成する必要があります。 UGS CLI を使用して、以下のleaderboard.lbnew-fileファイル名はリーダーボード ID に対応します。以下の設定でugs leaderboards new-file leaderboard
leaderboard.lbUGS CLI ツールを使用してファイルをデプロイします。{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/leaderboards.schema.json", "SortOrder": "asc", "UpdateType": "keepBest", "Name": "leaderboard"}
リーダーボードを作成したので、そこにスコアを追加できます。ugs deploy leaderboard.lb
任意: リーダーボードへのスコアの追加
以下の Cloud Code スクリプトを実行して、Unity Cloud Dashboard からリーダーボードにスコアを追加できます。すべてのテスト実行でプレイヤー ID トークンを再生成して、新しいプレイヤーのスコアを生成してください。
JavaScript
const { LeaderboardsApi } = require("@unity-services/leaderboards-1.1");const _ = require("lodash-4.17");module.exports = async ({ params, context, logger }) => { const leaderboardsApi = new LeaderboardsApi({ accessToken: context.accessToken }); const leaderboardID = "leaderboard"; var randomScore = _.random(1, 100); try { await leaderboardsApi.addLeaderboardPlayerScore(context.projectId, leaderboardID, context.playerId, { score: randomScore }); } catch (err) { logger.error("Failed to add score to the leaderboard", { "error.message": err.message }); }};
score-submitted イベントを調べる
Leaderboards サービスは、新しいスコアがリーダーボードに送信されたときにscore-submittedイベントは、イベントペイロードをパラメーターとして Cloud Code に渡します。 詳細については、Leaderboards: スコア送信 を参照してください。{ "leaderboardId": "leaderboard", "updatedTime": "2019-08-24T14:15:22Z", "playerId": "5drhidte8XgD4658j2eHtSljIAzd", "playerName": "Jane Doe", "rank": 42, "score": 120.3, "tier": "gold"}
Cloud Code の設定
スコアが破られたプレイヤーにプッシュメッセージを送信するモジュールエンドポイントを定義します。 以下のようなコンテンツでSendPushNotificationモジュールをデプロイします。 モジュールのデプロイ方法を学習するには、Hello World のデプロイ を参照してください。using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;namespace LeaderboardsNotification;public class LeaderboardsNotification{ private readonly ILogger<LeaderboardsNotification> _logger; public LeaderboardsNotification(ILogger<LeaderboardsNotification> logger) { _logger = logger; } [CloudCodeFunction("SendPlayerMessage")] public async Task SendPlayerMessage(IExecutionContext context, IGameApiClient gameApiClient, PushClient pushClient, string playerId, string playerName, string leaderboardId, double score) { try { var closestPlayers = await gameApiClient.Leaderboards.GetLeaderboardScoresPlayerRangeAsync(context, context.ServiceToken, new Guid(context.ProjectId), leaderboardId, playerId, 1); if (closestPlayers.Data.Results.Count != 0) { var player = closestPlayers.Data.Results[^1]; string message = $"The player {playerName} has just beaten your score of {player.Score} on the {leaderboardId} leaderboard by {score-player.Score} points!"; await pushClient.SendPlayerMessageAsync(context, message, "Information", player.PlayerId); } } catch (ApiException e) { _logger.LogError("Failed to send push notification to player {playerId}. Error: {Error}", playerId, e.Message); throw new Exception($"Failed to send push notification to player {playerId}. Error: {e.Message}"); } }}public class ModuleConfig : ICloudCodeSetup{ public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(PushClient.Create()); config.Dependencies.AddSingleton(GameApiClient.Create()); }}
トリガーの設定
Cloud Code リソースを Leaderboardsscore-submittednew-file以下の設定でugs triggers new-file triggers-config
triggers-config.trUGS CLI ツールを使用して設定をデプロイします。{ "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json", "Configs": [ { "Name": "score-beaten-message", "EventType": "com.unity.services.leaderboards.score-submitted.v1", "ActionUrn": "urn:ugs:cloud-code:LeaderboardsNotification/SendPlayerMessage", "ActionType": "cloud-code" } ]}
成功レスポンスは以下のようになります。ugs deploy triggers-config.tr
サンプルトリガーは、プレイヤーがサインアップしたときに Cloud Code モジュール関数を実行します。Deployed:triggers-config.tr
結果の検証
結果を検証するには、プッシュメッセージをサブスクライブする Unity プロジェクトを設定し、前に作成した Cloud Code スクリプト を使用してリーダーボードに新しいスコアを送信します。前提条件
プッシュメッセージをサブスクライブするには、Cloud Code SDK をインストールし、Unity Gaming Services プロジェクト を Unity エディターにリンクする必要があります。プロジェクトのリンク
Unity Gaming Services プロジェクト を Unity エディターにリンクします。UGS プロジェクト ID は Unity Cloud Dashboard にあります。- Unity エディターで、Edit (編集) > Project Settings (プロジェクト設定) > Services (サービス) の順に選択します。
-
プロジェクトをリンクします。
プロジェクトに Unity プロジェクト ID がない場合:- Create a Unity Project ID (Unity プロジェクト ID の作成) > Organizations (組織) の順に選択し、ドロップダウンから組織を選択します。
- Create project ID (プロジェクト ID を作成) を選択します。
既存の Unity プロジェクト ID がある場合:- Use an existing Unity project ID (既存の Unity プロジェクト ID を使用) を選択します。
- ドロップダウンから組織とプロジェクトを選択します。
- Link project ID (プロジェクト ID をリンク) を選択します。
UnityEditor.CloudProjectSettings.projectIdSDK のインストール
Unity エディターの最新の Cloud Code パッケージをインストールするには、以下を行います。- Unity エディターで、Window (ウィンドウ) > Package Manager (パッケージマネージャー) を開きます。
- Package Manager で、Unity Registry (Unity レジストリ) のリストビューを選択します。
- を検索するか、リストから Cloud Code パッケージを探します。
com.unity.services.cloudcode - このパッケージを選択し、Install を選択します。
Monobehaviour スクリプトの作成
プレイヤーレベルのメッセージをサブスクライブするには、MonobehaviourMonoBehaviourusing System;using System.Threading.Tasks;using Newtonsoft.Json;using Unity.Services.Authentication;using Unity.Services.CloudCode;using Unity.Services.CloudCode.Subscriptions;using Unity.Services.Core;using UnityEngine;namespace CloudCode{ public class CloudCodePushExample : MonoBehaviour { async void Start() { await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); Debug.Log(AuthenticationService.Instance.PlayerId); await SubscribeToPlayerMessages(); } // This method creates a subscription to player messages and logs out the messages received, // the state changes of the connection, when the player is kicked and when an error occurs. Task SubscribeToPlayerMessages() { // Register callbacks, which are triggered when a player message is received var callbacks = new SubscriptionEventCallbacks(); callbacks.MessageReceived += @event => { Debug.Log(DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")); Debug.Log($"Got player subscription Message: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.ConnectionStateChanged += @event => { Debug.Log($"Got player subscription ConnectionStateChanged: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.Kicked += () => { Debug.Log($"Got player subscription Kicked"); }; callbacks.Error += @event => { Debug.Log($"Got player subscription Error: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; return CloudCodeService.Instance.SubscribeToPlayerMessagesAsync(callbacks); } }}
MonobehaviourGot player subscription Message: { "data_base64": <BASE64-ENCODED-DATA>, "time": "2023-09-19T10:26:40.436878688Z", "message": "The player AdjacentMowingToga#7 has just beaten your score of 120.3 on the my-leaderboard leaderboard by 51.3 points!", "specversion": "1.0", "id": <ID>, "source": "https://cloud-code.service.api.unity.com", "type": "com.unity.services.cloud-code.push.v1", "projectid": <PROJECT-ID>, "environmentid": <ENVIRONMENT-ID>, "correlationid": <CORRELATION-ID>, "messagetype": "Information"}