Open a inventory

This page describes how to open an inventory to a player.

Retrieve the InventoryViewer

An InventoryViewer is an encapsulation of a player and its associated inventories, which are handled in the an InventoryViewManager. This class provides methods for opening / closing inventories and to navigate through the player's inventory history.

An InventoryViewer is created automatically for each player joining the server and then stored in an InventoryService. The viewer associated to a player can be retrieved as in the following code:

InventoryService inventoryService = ... ;
Player player = ... ;

// Retrieve the InventoryViewer instance associated to a player.
InventoryViewer viewer = inventoryService.getInventoryViewer(player);

Retrieve the InventoryProvider

An InventoryProvider is responsible for providing an inventory. All the providers are stored in an InventoryService and can be retrieved as in the following code:

InventoryService inventoryService = ... ;

// Retrieve the provider for an inventory.
Optional<InventoryProvider> optional = inventoryService.getProvider("inventory-id");

Example

The following code shows how you can open an inventory to a player.

InventoryService inventoryService = ... ;
Player player = ... ;

InventoryViewer viewer = inventoryService.getInventoryViewer(player);

inventoryService.getProvider("inventory-id").ifPresent(provider -> {
    CraftVentory inventory = provider.createInventory(this.service, player);
    viewer.getViewManager().openView(inventory);
});

The open() and close() methods available in the CraftVentory interface should never be used to open or close an inventory. You must use the methods from the InventoryViewManager interface instead.

Last updated