Skip to content

Cloud Scripts

Jiufen edited this page Mar 31, 2021 · 1 revision

Cloud scripts are a way in which you can delegate the execution of certain code to the playfab cloud.

☁Creating Cloud Scripts☁

We will need to go to the automation section in our playfab dashboard:

And go to the revisions tab:

In the revisions tab we will found the main script that will have all the functions that we can execute through the cloud functionality. The code is written in javascript, here is an example of a code that update the player statistics:

handlers.UpdatePlayerStats = function (args, context) {
    var request = {
        PlayFabId: currentPlayerId, Statistics: [{
                StatisticName: "PlayerHealth",
                Value: args.playerHealth
            },
            {
                StatisticName: "PlayerLevel",
                Value: args.playerLevel
            },
            {
                StatisticName: "MaxScore",
                Value: args.maxScore
            }]
    };
    // The pre-defined "server" object has functions corresponding to each PlayFab server API 
    // (https://api.playfab.com/Documentation/Server). It is automatically 
    // authenticated as your title and handles all communication with 
    // the PlayFab API, so you don't have to write extra code to issue HTTP requests. 
    var playerStatResult = server.UpdatePlayerStatistics(request);
    return { messageValue: "Variables Updated" };
};

🕹Accessing Cloud Scripts trough our unity code🕹

To access the cloud through our unity code we need to use the ExecuteCloudScript method that the PlaFab API provide us:

this code, takes an onSuccess and an onFailure function, like the previous methods we had used in the past.

// Build the request object and access the API
public void StartCloudUpdateStats()
{
    PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest()
    {
        FunctionName = "UpdatePlayerStats", // Arbitrary function name (must exist in your uploaded cloud.js file)
        FunctionParameter = new { playerHealth = this.playerHealth, playerLevel = this.playerLevel, maxScore = this.maxScore }, // The parameter provided to your function
        GeneratePlayStreamEvent = true, // Optional - Shows this event in PlayStream
    }, OnCloudUpdateStats, OnErrorShared);
}

private void OnCloudUpdateStats(ExecuteCloudScriptResult result) {
    // CloudScript returns arbitrary results, so you have to evaluate them one step and one parameter at a time
    Debug.Log(PlayFabSimpleJson.SerializeObject(result.FunctionResult));
    JsonObject jsonResult = (JsonObject)result.FunctionResult;
    object messageValue;
    jsonResult.TryGetValue("messageValue", out messageValue); // note how "messageValue" directly corresponds to the JSON values set in CloudScript
    Debug.Log((string)messageValue);
}

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

Clone this wiki locally