UnityからPlayFabのCloudFunctionを呼び出してみる


PlayFabにはCloudFunctionというサーバーサイドで処理するスクリプトを定義できます。
便利そうなので試しにUnityから呼び出してみます。

環境

  • Unity 2019.2.2f1
  • PlayFab SDK 2.75.191001

呼び出すスクリプトを確認

まずは管理画面でCloudScriptを確認します。(最初から用意されているものを使います)

自動化 -> Cloud Script -> リビジョン
でソースコードを確認できます。

最初からhelloWorldという関数が入っているのでそれを使います。

hello_world.js
handlers.helloWorld = function (args, context) {
    var message = "Hello " + currentPlayerId + "!";
    log.info(message);

    var inputValue = null;
    if (args && args.inputValue)
        inputValue = args.inputValue;
    log.debug("helloWorld:", { input: args.inputValue });

    return { messageValue: message };
};

Unityから呼び出す

Unity側で以下のようなスクリプトを用意して実行してみます。

PlayFabDemo.cs
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine;

public class PlayFabDemo : MonoBehaviour
{
    public void Start()
    {
        var loginRequest = new LoginWithCustomIDRequest {CustomId = "MyCustomId", CreateAccount = true};
        PlayFabClientAPI.LoginWithCustomID(loginRequest, OnLoginSuccess, OnError);
    }

    private void OnLoginSuccess(LoginResult loginResult)
    {
        Debug.Log("ログイン成功");

        var helloWorldRequest = new ExecuteCloudScriptRequest()
        {
            FunctionName = "helloWorld",
            FunctionParameter = new {inputValue = "naichilab"},
            GeneratePlayStreamEvent = true
        };
        PlayFabClientAPI.ExecuteCloudScript(helloWorldRequest, OnHelloWorldSuccess, OnError);
    }

    private void OnHelloWorldSuccess(ExecuteCloudScriptResult helloWorldResult)
    {
        Debug.Log(helloWorldResult.FunctionResult);
    }

    private void OnError(PlayFabError error)
    {
        Debug.Log(error.GenerateErrorReport());
    }
}

コールバック多くて見辛いですがやってることは以下の2つです。

  1. ログインする
  2. ログイン成功したらCloudFunction helloWorld を呼び出す

実行するとそれっぽいログが出てます。

よい〜。

何が起きた?

こんな感じですね。

PlayFabClientAPI.ExecuteCloudScript でPlayFab上の helloWorld を呼び出しています。

便利〜〜〜

ログを確認する

CloudFunction側にある以下のログがどこに書かれるか確認してみます。

  • log.info(message);
  • log.debug("helloWorld:", { input: args.inputValue });

タイトルの概要 -> PlayStreamモニター
を開いておきます。

この状態でUnity側を実行すると、イベントストリームが流れます

Unity側で GeneratePlayStreamEvent = true としておくと、ここにCloudScriptの実行履歴が流れます。

そこにある Information マークを押すと、実行ログの詳細を確認できます。

ちゃんと2件のログが入っていました。

まとめ

  • PlayFab上で関数を定義(jsで書く)
  • Unityから ExecuteCloudScript を使って関数を実行する

こんな感じで簡単に使えました。引数も戻り値も扱えるのでかなり自由度は高いですね。

便利〜〜〜。

リンク