question

Leyla Ahmedzadeh avatar image
Leyla Ahmedzadeh asked

How to send and receive value from Cloud Script using Unity C#

So I am creating a 1vs1 multiplayer game where the players have to send 3 values to the Cloud script. In the cloud script, the values will be processed then it will return a result to both players. I want to create C# cloud script using azure-functions. The environment is set in vscode. I can create azure function and add this function to PlayFab => Automation => Cloud Script => Functions but unfortunately i can't send or receive value from 1 player to another. I am using this piece of code from the documentation in unity. How can I send, process, and receive value from the Cloud Script using C# azure-function? Thanks in advance!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PlayFab;
using PlayFab.ClientModels;
using PlayFab.PfEditor.Json;


public class NetworkManager : MonoBehaviour
{
    private string playerName = "TestName";
    private int playerIndex = 1;
    private bool isSelected;


    // Build the request object and access the API
    public void CloudSendPlayerValues()
    {
        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest()
        {
            FunctionName = "helloWorld", // Arbitrary function name (must exist in your uploaded cloud.js file)
            FunctionParameter = new
            {
                name = playerName,
                playerIndex = playerIndex,
                isSelected = isSelected


            }, // The parameter provided to your function
            GeneratePlayStreamEvent = true, // Optional - Shows this event in PlayStream
        }, OnCloudSendPlayerValues, OnErrorShared) ;
    }


    private void OnCloudSendPlayerValues(ExecuteCloudScriptResult result)
    {
        // CloudScript (Legacy) returns arbitrary results, so you have to evaluate them one step and one parameter at a time
        Debug.Log(JsonWrapper.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 (Legacy)
        Debug.Log((string)messageValue);
    }


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

CloudScript
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Gosen Gao avatar image
Gosen Gao answered

If you want to send an int value to the Azure Function, subtract 1 from this value, then return it to the caller. Such operation can be done on the client side, you don't have to call an Azure Function. If you just want to get a sample, then you can refer to the code below.

Azure Function

[FunctionName("HttpTrigger1")]
public static async Task<int> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",Route = null)] HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    FunctionExecutionContext<dynamic> context = JsonConvert.DeserializeObject<FunctionExecutionContext<dynamic>>(await req.ReadAsStringAsync());
    var args = context.FunctionArgument;
    int value = args["Value"];
    value--;
    return value;
}

Client side

PlayFabCloudScriptAPI.ExecuteFunction(new PlayFab.CloudScriptModels.ExecuteFunctionRequest
{
    FunctionName = "HttpTrigger1",
    FunctionParameter = new
    {
        Value = 11
    },
    GeneratePlayStreamEvent = false
},
result =>
{
    if (result.FunctionResultTooLarge ?? false)
    {
        Debug.Log("This can happen if you exceed the limit that can be returned from an Azure Function, See PlayFab Limits Page for details.");
        return;
    }
    Debug.Log($"The {result.FunctionName} function took {result.ExecutionTimeMilliseconds} to complete");
    Debug.Log($"Result: {result.FunctionResult.ToString()}");
},
error =>
{
    Debug.LogError(error.GenerateErrorReport()); 
});

For more info, you can refer to Quickstart: Writing a PlayFab CloudScript using Azure Functions.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Gosen Gao avatar image
Gosen Gao answered

According to your description, it seems like you want both players to receive an Azure Function’s result. Since the Azure Function is a serverless solution and is called via RESTful API, so only the caller can receive the function result. May I know what is your scenario so that we can discuss it in detail?

3 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Leyla Ahmedzadeh avatar image Leyla Ahmedzadeh commented ·

One of the use case scenarios is sending int value to the cloud script. Inside of this cloud script, I want to subtract 1 from this value. Then return it to the player in unity. What is the structure of sending value and processing this value inside of cloud script (C# azure function)

2 Likes 2 ·
Gosen Gao avatar image Gosen Gao Leyla Ahmedzadeh commented ·

So you mean that the information of the change of the Int value is obtained by both players, right? The Azure Function cannot send the processed result to the specified player, only the caller can receive the result in the form of return value after the Azure Function is executed. You can create a SharedGroupData to store such a value, so that both players in the SharedGroup can modify the value and know when the value changes.

0 Likes 0 ·
Leyla Ahmedzadeh avatar image Leyla Ahmedzadeh Gosen Gao commented ·

I understood that the Azure function is serverless and other players will not be able to receive the function result. But i can't even create a C# Azure function that only the caller can receive the function result. I want to create C# Azure function that the caller will call and send value to this cloud script and receive processed value. As I mentioned in the first reply (Not the other player but the caller itself). I need the structure of C# azure function to receive and return processed value to caller

0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.