LoginSignup
11
3

More than 3 years have passed since last update.

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

Posted at

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

環境

  • Unity 2019.2.2f1
  • PlayFab SDK 2.75.191001

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

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

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

スクリーンショット 2019-10-07 23.54.37.png

最初から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 を呼び出す

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

スクリーンショット 2019-10-07 23.59.16.png

よい〜。

何が起きた?

image.png

こんな感じですね。

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

便利〜〜〜

ログを確認する

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

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

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

スクリーンショット 2019-10-08 0.08.19.png

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

スクリーンショット 2019-10-08 0.09.17.png

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

スクリーンショット 2019-10-08 0.09.54.png

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

スクリーンショット 2019-10-08 0.10.20.png

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

まとめ

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

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

便利〜〜〜。

リンク

11
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
3