Reset inventory

Hi guys,

Just a quick question about the inventory API. I would like to save the whole inventory (armor, hotbar, etc.) of a player and give him back later. But how can I keep the exact same inventory: each item should be placed back in the same slot ?

For now, I manage to give back the inventory without keeping the item position. This is how I do that:

    Inventory inventory = ... ; 
    player.getInventory().clear();
    for( Inventory slot: inventory.slots() )
    {
        Optional<ItemStack> itemStack = slot.poll();

        if( itemStack.isPresent()  )
            player.getInventory().offer( itemStack.get() );
    }

This has two drawbacks:

  • Positions are not kept
  • Same items are stacked

Thank’s in advance ! :slightly_smiling:

1 Like

I would like to know this as well.

Firstly, go have a read over https://github.com/SpongePowered/SpongeAPI/pull/443 - that’s the full design document for the Inventory system.

@Mumfrey, maybe you’d know how to best tackle this?

Thank you, I found GridInventory in the design document which could perform what I need. Here is what I tried, without success:

    GridInventory playerGridInventory = player.getInventory().query(GridInventory.class);
    Vector2i dim = playerGridInventory.getDimensions();

    for(int i=0; i<dim.getX(); ++i)
    {
        for(int j=0; j<dim.getY(); ++j)
            playerGridInventory.set(i,j, ItemStack.builder().itemType(ItemTypes.DIAMOND_SWORD).quantity(1).build() );
    }

Is it the right way ?

What do you mean? If you mean that only part of the player’s inventory gets filled, that’s because the full inventory isn’t just a grid. The hotbar is seperate and not a grid, as is the armour and crafting.

I think best way to do what you want is to use Inventory#iterator(). This will allow you to get all items in the hotbar, inventory and armor slots. I’m not certain how you’d restore this, however.

The grid if of size 3*9 as expected. But with the previous code nothing is filled. It is also the case with:

Hotbar hotbar = player.get().getInventory().query(Hotbar.class);
hotbar.set(new SlotIndex(0), itemStack);