Store inventory items in variables

Hi!

I would like a variable to store the number of items my party has at a given moment. (Not the amount of a certain item, but the total number of different items.)
I would also like a variable to store the itemID of the second item of the inventory.

I tried checking the Scene_ItemBase and Scene_Item parts of the main scripts but I couldn't figure out how MZ creates the list as I don't really understand JS. Maybe it creates an array, but I don't know how to access and use that.

Could anyone help figure out how I could store these informations in variables? What script should I use?

Thanks!
Number of different inventory items:
$gameParty.items().filter(item, index => this.indexOf(item)==index).length

If you actually meant the total number of items in inventory, including duplicates, that's just
$gameParty.items().length

And then $gameVariables.setValue(X, $gameParty.items()[1].id); where X is the ID of the variable to store the second item's ID in. Be careful that you only use it when you know there are at least 2 items in inventory, or check for the variable not to be undefined before you use it for anything.
Thank you very much!

Last question: if there is only 1 item in the inventory, how could I get that item's ID?
Note that $gameParty.items() gets a list of database Item references (not Weapons or Armors). By default it has one entry per item, irrespective of the quantity of that item in inventory. (If you wanted item quantity, you'd use $gameParty.numItems or the built-in Control Variables -> Game Data option.)

E.g. if the inventory has 5 x Potion (Item ID 1), 2 x Apple (Item ID 8), and 1 x Sword (Weapon ID 1):
  • $gameParty.items().length will be 2 (Potion, Apple);
  • $gameParty.items()[0] will be $dataItems[1] (Potion);
  • $gameParty.items()[0]?.id || 0 will be 1;
  • $gameParty.items()[1] will be $dataItems[8] (Apple);
  • $gameParty.items()[1]?.id || 0 will be 8;
  • $gameParty.items()[2] will be undefined;
  • $gameParty.items()[2]?.id || 0 will be 0.

  • const i = $gameParty.items(); i[i.length > 1 ? 1 : 0]?.id || 0 would be 8 (Apple ID).
    • If the Apples were removed (so there's only one type of Item in the inventory) then it would be 1 (Potion ID).
?. is called the optional chaining operator (technical link), which I've used here, along with the short-circuit behaviour of logical OR || (technical link), as a failsafe for undefined item references.

If you want to check other item types (Weapon/Armor), you can replace items() with:
  • armors() - Armors only;
  • weapons() - Weapons only;
  • equipItems() - Weapons and Armors only;
  • allItems() - Items, Weapons, and Armors.
Thank you so much both of you! It works exactly how I wanted!

Original thread: https://forums.rpgmakerweb.com/threads/store-inventory-items-in-variables.148605/