3

I am trying to check to see if a player has an item in their inventory, and remove one of them if they do. Here is what I have now:

Material ammomat = parseMaterial(plugin.getConfig().getString("game.ammo_material"));

ItemStack ammo = new ItemStack(ammomat, 1);

if(p.getInventory().contains(ammomat, 1)){
    p.getInventory().removeItem(ammo);
    p.updateInventory();
}

It gets whether they have the item, but it won't remove one.

How can I remove one item from the player's inventory?

Jojodmo
  • 23,357
  • 13
  • 65
  • 107
IcyRelic
  • 167
  • 1
  • 3
  • 14

2 Answers2

4

If you want to remove just one item, you could loop through the items in the player's inventory, and then check if the material matches what you want. If it does, you could remove one item from the ItemStack

It could look something like this:

for(int i = 0; i < p.getInventory().getSize(); i++){
  //get the ItemStack at slot i
  ItemStack itm = p.getInventory().getItem(i);
  //make sure the item is not null, and check if it's material is "mat"
  if(itm != null && itm.getType().equals(mat){
    //get the new amount of the item
    int amt = itm.getAmount() - 1;
    //set the amount of the item to "amt"
    itm.setAmount(amt);
    //set the item in the player's inventory at slot i to "itm" if the amount
    //is > 0, and to null if it is <= 0
    p.getInventory().setItem(i, amt > 0 ? itm : null);
    //update the player's inventory
    p.updateInventory();
    //we're done, break out of the for loop
    break;
  }
}

So, here's what your code could look like:

Material ammomat = parseMaterial(plugin.getConfig().getString("game.ammo_material"));

for(int i = 0; i < p.getInventory().getSize(); i++){
  ItemStack itm = p.getInventory().getItem(i);
  if(itm != null && itm.getType().equals(ammomat){
    int amt = itm.getAmount() - 1;
    itm.setAmount(amt);
    p.getInventory().setItem(i, amt > 0 ? itm : null);
    p.updateInventory();
    break;
  }
}
Jojodmo
  • 23,357
  • 13
  • 65
  • 107
-1

Well to remove one item at a time you would just specify the amount after the item: p.getInventory().removeItem(ammo, 1);

But your if statement is just testing if they have the item then removing it so it would still remove all of them at the same time for how fast the program will run.

So if you're making guns, you should probably make a method for shooting (I don't know if you already did that).

This is way too late but still, the way the other answer suggested would not work the best.

helencrump
  • 1,351
  • 1
  • 18
  • 27
Billy
  • 1