question

grumn avatar image
grumn asked

PlayFab docs in json but Unity is C#

I'm trying to get familiar with PlayFab and Unity. At this point I'm trying to make an API call that is beyond just creating an account, logging in and calling the players username up. I want to pull up the players virtual currency I created called "AU", using the call PlayFabClientAPI.GetPlayerCombinedInfo. I'm confused about how to read and implement the PlayFab documentation. All the examples are written in Json and I've gotten lucky converting them over to C# so far but this GetPlayerCombinedInfo is stumping me. And if I can't figure this out from their example code then I can't get any help from their documentation in the future.

My question is, how do I interpret these json inputs into C#?

https://api.playfab.com/documentation/client/method/GetPlayerCombinedInfo

This is a sample request.

POST https://{ {TitleID}}.playfabapi.com/Client/GetPlayerCombinedInfo Content-Type: application/json X-Authentication: <user_session_ticket_value> {

"PlayFabId": "4027527BF22653D1",

"InfoRequestParameters": {

"GetUserAccountInfo": true,

"GetUserInventory": false,

"GetUserVirtualCurrency": true,

"GetUserData": true,

"UserDataKeys": [

"preferences",

"progress"

],

"GetUserReadOnlyData": false,

"GetCharacterInventories": false

, "GetCharacterList": false,

"GetTitleData": false,

"GetPlayerStatistics": false,

"GetPlayerProfile": false } }

and this is my interpretation of it in C#

var request = new GetPlayerCombinedInfoRequest() {

InfoRequestParameters = {

GetCharacterInventories = false,

GetCharacterList = false,

GetPlayerProfile = false,

GetPlayerStatistics = true,

GetTitleData = false,

GetUserAccountInfo = false,

GetUserData = false,

GetUserInventory = false,

GetUserReadOnlyData = false,

GetUserVirtualCurrency = true

}

};

and here is the call and OnSuccess function (the script doesn't get here before it throws an error)

PlayFabClientAPI.GetPlayerCombinedInfo(request, UpdateGold, OnFailure);

}

void UpdateGold(GetPlayerCombinedInfoResult result)

{

int value = 0;

result.InfoResultPayload.UserVirtualCurrency.TryGetValue("AU", out value);

Debug.Log(value);

gold.text = "Gold: " + value.ToString();

}

this compiles fine and then return a null object error at the first line of code up there, it cant create a request object.

Am I writing the InfoRequestParameters wrong?

Why doesn't the playfab documentation have any examples in c#?

How do I write a correct GetPlayerCombinedInfoRequest call in c#?

var request = new GetPlayerCombinedInfoRequest() { };

I feel like I'm not writing the InfoRequestParameters correctly or something.

Thanks for any help you can offer!

unity3d
10 |1200

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

Seth Du avatar image
Seth Du answered

For your questions, I will show you the way to use GetPlayerCombinedInfo API call and a data-retrieval sample In Unity C#, please see my code along with the documentation:

PlayFabClientAPI.GetPlayerCombinedInfo(
    new GetPlayerCombinedInfoRequest {
        // check document to see the class of a property in the request
        InfoRequestParameters = new GetPlayerCombinedInfoRequestParams()
        {
            // GetPlayerCombinedInfoRequestParams has many boolean attributes
            GetCharacterInventories = true,
            GetPlayerStatistics = true
        },

        // PlayFabId is not required though
        PlayFabId = "xxxxxxxxxx"
    },
    OnSuccess=> 
    {
        // what we got from success callback is InfoResultPayload and playfabID
        GetPlayerCombinedInfoResultPayload PlayerPayload = OnSuccess.InfoResultPayload;
        // for example, retrieve statistics from PlayerPayload
        List<StatisticValue> mystatistics = PlayerPayload.PlayerStatistics;
    },
    OnFail=> { }
    );

The basic idea is that you need to make use of Unity SDK. In normal circumstance, you should not worry about JSON in the communication because all the data you need has been encapsulated into class, variables or list, and you need to check documentation to see which they belong to. JSON string are usually for manually storing data such as in Player Data. Be aware that C# is strongly typed, hence you need to check the types of objects before you use it.

10 |1200

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

Justin avatar image
Justin answered

It is first important to realize an API call can be setup nested (with lambda or " => ") or as separate methods like this:

public void GetMyInventory()
{
	// Build the request, Then pass it to API call

	var request = new GetUserInventoryRequest(); //gets all results
						     
	PlayFabClientAPI.GetUserInventory(request, GetMyInventorySuccess, 
        	GetMyInventoryError); //make API call
}

private void GetMyInventorySuccess(GetUserInventoryResult result)
{
	Debug.Log("GetUserInventorySuccess: " + result);
	Debug.Log("Do Something With Inventory Here!");
}

private void GetMyInventoryError(PlayFabError error)
{
	Debug.Log("GetUserInventoryError: " + error);
}

VirtualCurrency can be accessed as a batch with "PlayFabClientAPI.GetPlayerCombinedInfo" as you suggested or you can call just "PlayFabClientAPI.GetUserInventory".

You can have access to both if needed. So, my method is nested with lambdas (=>) and "GetUserInventory" looks like this:

public readonly Dictionary<string, int> virtualCurrency = 
	new Dictionary<string, int>();

public readonly List<ItemInstance> playerInventory = new List<ItemInstance>();

// This is a sorted, collated structure built from playerInventory.
// By default, this will only grab items that are in the primary catalog
public readonly Dictionary<string, InventoryCategory> inventoryByCategory = 
	new Dictionary<string, InventoryCategory>();

public void GetUserInventory(Action callback = null)
{        
    PlayFabClientAPI.GetUserInventory(new GetUserInventoryRequest(), 
	(GetUserInventoryResult result) =>
    {
        virtualCurrency.Clear();     // Local Dictionaries for VirtualCurrency & 
        playerInventory.Clear();     // InventoryItems
        inventoryByCategory.Clear();

        foreach (var eachPair in result.VirtualCurrency)     //VIRTUAL CURRENCY//
        {
            virtualCurrency.Add(eachPair.Key, eachPair.Value);
            Debug.Log("Virtual Currency: " + eachPair.Key);

            if (eachPair.Key == "GC")
            {
                Debug.Log("GC currency found");
                MessagingData.UpdateCurrencyValue(eachPair.Value);
            }
            else
            {
                Debug.Log("GC currency was not found!");
            }
        }

        foreach (var eachItem in result.Inventory)           //PLAYER INVENTORY//
        { 
            playerInventory.Add(eachItem);
            Debug.Log("Inventory Item: " + eachItem.ItemId);
        }

        if (GameDataManager.Instance.catalogItems.Count > 0)
        {
            foreach (var item in playerInventory)     //PLAYER INV. BY CATEGORY//
            {
                if (inventoryByCategory.ContainsKey(item.ItemId))
                    continue;

                var catalogItem = GameDataManager.Instance.GetCatalogItemById(item.ItemId);
                if (catalogItem == null)
                    continue;

                var items = playerInventory.FindAll(x => 
			{ return x.ItemId.Equals(item.ItemId); });
                
                inventoryByCategory.Add(item.ItemId, 
			new InventoryCategory(item.ItemId, catalogItem, items);
            }
        }

        if (callback != null)
            callback();
        
    }, (PlayFabError error) =>
    {
        Debug.Log("Get User Inventory Error: " + error);
    });        
}
1 comment
10 |1200

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

Justin avatar image Justin commented ·

Sorry, I forgot to mention that your main question tripped me up too.. it was pretty complicated as you don't really know what you are looking at when you land here: "http://playfabapi.com/Client/GetPlayerCombinedInfo

The way I understand it is like this: (please correct me if I am wrong here :) )

It is showing you what the actual call looks like as sent to PlayFab. Everything you build into the request is turned into an efficient json packet which is then read by PlayFab's servers and then the servers send back the "result" if succesful and the "error" if the request fails. So, you don't have to deal with the json directly.

(I have only had to deal with parsing json data when doing reciept validation directly through GooglePlay or IOS using UnityIAP - If you need a clue here I can share info links and code).

I hope this helps. Cheers!

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.