Skip to content

Instantly share code, notes, and snippets.

@JoshuaStrunk
Last active June 3, 2019 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaStrunk/7ac993fc87bd8d3256ab2c280846995c to your computer and use it in GitHub Desktop.
Save JoshuaStrunk/7ac993fc87bd8d3256ab2c280846995c to your computer and use it in GitHub Desktop.
handlers.getItemPositionAndDamage = function(args) {
var getCatalogItemsResponse = server.GetCatalogItems({}); //This returns the primary catalog for our game if we wanted a different version we must specify CatalogVersion in the argument
var catalogItems = getCatalogItemResponse.Catalog; //We must get the catalog field out of the response object
var getUserInventoryResponse = server.GetUserInventory({ //This returns all the inventory items for the user who called ExecuteCloudScript()
PlayFabId: currentPlayerId
});
var userInventory = getUserInventoryResponse.Inventory; //We must get the Inventory field out of the response object
var firstItemInstance = userInventory[0]; //Gets the first item out of userInventory.
var firstItemInstanceUnencodedCustomData = firstItemInstance.CustomData; //Gets the unencoded JSON object of this items ItemInstance.CustomData
var firstItemInstanceInventoryPostion = firstItemInstanceUnencodedCustomData.InventoryPosition; //Get the InventoryPostion for this item
/*
Below is probably the most important piece of code in this script it is how
we get the CatalogItem information with only an ItemInstance object. It uses
the find function of JavaScript arrays (Array.prototype.find()) to iterate
through all the individual catalogItems in catalogItems. it then will return
the CatalogItem object which has the same ItemId as our ItemInstance;
*/
var catalogItemOfFirstItemInstance = catalogItems.find(function(catalogItem) {
return catalogItem.ItemId == firstItemInstance.ItemId;
});
var firstItemInstanceDescription = catalogItemOfFirstItemInstance.Description; //Using the found catalogItem we can now get the items Description.
var catalogItemEncodedCustomData = catalogItemOfFirstItemInstance.CustomData; //To get to the items CustomData first we get the JSON encoded as a string
var catalogItemUnencodedCustomData = JSON.parse(catalogItemEncodedCustomData); //Then we use JSON.parse(encodedJSON) to parse our encoded JSON string into an unencoded JSON object
var firstItemInstanceDamage = Number(catalogItemUnencodedCustomData.Damage); //And lastly we use the JSON object o get the items damage we use Number(object) to cast it to a number
return {
InventoryPosition: firstItemInstanceInventoryPostion,
Description: firstItemInstanceDescription,
Damage: firstItemInstanceDamage
};
};
@scuitino
Copy link

scuitino commented Jun 3, 2019

Thanks for this example! It helps me a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment