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?
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;
}
}