Good day, I need to do that if a player has something in his inventory that he doesn't have, then he takes it by command: Player has an item named "BOX" I'll give command / clear <player> <BOX> and it will take it from the inventory, thank you in advance.
I don't know how: D I do this for the first time how should it be? player # getInventory (). getNiecoContents (). forEach (c -> player # getInventory (). removeItem (c));
If you are removing an item I think .removeItem shuld work, if not, youll have to check every item on the inventory. You can get the contents of the inventiry with inv.getContents()
Player#getInventory will get you the inventory contents. You can just set the item amount to 0, it will automatically remove the item then.
Code (Text): package cz.veverka.baryocleaner; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.Arrays; public class ClearCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player player = Bukkit.getPlayer(args[0]); String searchName = args[1]; Inventory inventory = player.getInventory(); inventory.setContents(Arrays.stream(inventory.getContents()).filter(it -> it.getDisplayName().equals("test")).toArray(ItemStack[]::new)); player.updateInventory(); return false; } } Dont work get.DisplayName()
Display name is located within the item meta. Not every item has a displayname. You may access ItemMeta via ItemStack#getItemMeta. Make sure that the item is not null. Do not use streams without knowing what they are for. You are stripping away the structure of the inventory contents like that. You may iterate over the inventory directly, it extends an itemstack collection. You can just check the display name within there. Make sure to check if there is an item name listed there. Just run a #setAmount instead.
try this. not sure if you can just create an itemstack and add a display name, and then just player.getInventory().remove(item); but this is sure to work. (made a loop for every item in the inventory and check if the item has the display name, and if it does, setting the item to 0. also, make sure to check if there is a display name before trying to get a display name, to avoid getting npe's. Code (Text): @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { Player player = (Player) sender; for(ItemStack item : player.getInventory().getContents()) { if(item.getItemMeta().hasDisplayName()) { if(item.getItemMeta().getDisplayName().equals("Custom Item")) { item.setAmount(0); } } } } return false; } }