Skip to content

Inventory

Lenni0451 edited this page Jan 4, 2023 · 2 revisions

The inventory module is a complete reimplementation of the minecraft inventory handling code

Inventory Holder

The InventoryHolder class is the owner and tracker for all open inventories and the player inventory.
It contains some extra information needed for some inventory:

Name Description
creativeMode Whether the player is in creative mode or not
xpLevel The player's current xp level

To create a new inventory holder you first need to create a new player inventory, player container and recipe registry:

InventoryHolder<?, ?, ?> inventoryHolder = new InventoryHolder<>(new PlayerInventory_v1_7<>(), i -> new PlayerContainer_v1_7(i, recipeRegistry));

Opening an inventory

To open a new inventory you need to call the setOpenContainer method with a new container instance:

inventoryHolder.setOpenContainer(new ChestContainer_v1_7<>(windowId, playerInventory, 3*9));

Closing an inventory

To close the currently open inventory just call the setOpenContainer method with null.
The getOpenContainer method will return the player container if no other container is open.

Handling inventory updates

Inventory clicks

Inventory clicks are the most important part of the inventory module and probably the only thing you will need to use except for directly setting the inventory contents.
To handle inventory clicks the container class has the click method implemented which takes a inventory holder, the clicked slot, the button and the inventory action.
You can just get the open container from the inventory holder and call the click method:

oldCursorStack = inventoryHolder.getOpenContainer().click(inventoryHolder, slot, button, action);

The old cursor stack is only used in older versions of minecraft and is always null in newer versions.

Setting slot contents

To set the contents of a slot directly you have to differentiate between inventory slots and container slots.

Inventory slots

To set inventory slots you first need to get the wanted inventory from the open container or use the player inventory:

if (usePlayerInventory) {
    inventory = inventoryHolder.getPlayerInventory();
} else {
    inventory = ((ChestContainer_v1_7) inventoryHolder.getOpenContainer()).getChestInventory();
}
inventory.setStack(slot, itemStack);

Container slots

To set container slots you need to get the slot first and then set the stack in the slot:

if (usePlayerContainer) {
    container = inventoryHolder.getPlayerInventoryContainer();
} else {
    container = inventoryHolder.getOpenContainer();
}
container.getSlot(slot).setStack(stack);
Clone this wiki locally