[Solved] Does a Player's Inventory Contain

Hello Everyone,

I wish to create a method, with the Sponge 4.2.0 API, in which it checks to see if a player has a blue stained glass block in their inventory; if so, send them a message. I believed the code below would suffice, but when tested, nothing happens. I’ve had myself carry one blue stained glass block, a stack of them, and plain stained blocks, but nothing seems to trigger the message. Any thoughts? Thanks!

    ItemStack BG = ItemStack.builder().itemType(ItemTypes.STAINED_GLASS).build();
    BG.offer(Keys.DYE_COLOR, DyeColors.BLUE);
    
    if(player.getInventory().contains(BG)){
    	player.sendMessage(Text.of(TextColors.BLUE, "You have a blue stained glass in your inventory my friend."));
    }

How many are in your inventory?

As per the javadocs: the size of the stacks is ignored if the stack size is set to -1, otherwise the stack sizes must match the supplied stacks exactly

If you want to query regardless of stack size, use ItemStack.of(ItemTypes.STAINED_GLASS, -1) (oh, btw ItemStack.of() is a bit cleaner, and is just a wrapper around the builder).

1 Like

Correction - due to a bug you’ll have to use BG.setQuantitity(-1).

Additionally, it seems that contains isn’t implemented even in 5.0.0 yet (oops?) but you can use the equivalent - !inv.query(itemStack).empty()

1 Like

Thank you @ZephireNZ! With your knowledge, I was able to fix my method.