当前位置: 首页 > 知识库问答 >
问题:

Bukkit从库存中删除项目

陆信瑞
2023-03-14

我试着查看玩家的物品清单中是否有物品,如果有,就移除其中一个。以下是我现在所拥有的:

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();
}

它获取他们是否拥有该项目,但不会删除一个。

如何从玩家的库存中移除一件物品?

共有2个答案

傅涵忍
2023-03-14

好吧,要一次删除一个项目,您只需指定项目后的金额:p.getInventory().removeItem(ammo,1);

但是您的if语句只是测试他们是否有该项目,然后将其删除,因此它仍然会同时删除所有项目,以确定程序运行的速度。

所以如果你在制造枪支,你可能应该制作一种射击方法(我不知道你是否已经这样做了)。

这为时已晚,但仍然,另一个答案建议的方式不会是最好的。

焦信鸥
2023-03-14

如果你只想移除一件物品,你可以循环浏览玩家库存中的物品,然后检查材料是否与你想要的相符。如果是,您可以从ItemStack中删除一项

它可能看起来像这样:

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

因此,您的代码可能是这样的:

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;
  }
}
 类似资料:
  • 我尝试只删除 1 个项目,或者当我使用打开的库存单击它时保留项目堆栈,但是,方法:,删除库存中的所有类似项目,如何只删除 1 个项目,或 1 ?

  • 我正在尝试创建多个文本文件的存档。有时这些文件会更新,当这些文件更新时,我使用 tar 中的 选项将这些文件附加到存档中。 假设我们有两个文件,test1.txt和test2.txt.这些文件被添加到存档test.tar. 用焦油 我得到的如预期: 现在,如果我更新test2.txt,并使用< code > tar-f test.tar-u test 2 . txt 将其添加到存档中。 我希望运行

  • 我有一个假设,它有8个项目A-H,现在我想从中删除存储在int数组中的1,3,5位置项目。我该怎么做。 我正试着和你一起做这件事 但在数组的第一个被删除的项被更改之后,在下一次迭代中它删除了错误的元素或给出异常。

  • 所以。烦人。 为简洁起见编辑: 类似问题的答案state将修复问题,但我做错了吗?因为它说它不匹配任何文件?也许是因为我运行了git重置?

  • 我正在尝试做一个Java线程,这个线程必须从一个MySQL数据库中删除所有的记录,超过7天。 在我的表中,我有一列包含如下日期:。

  • 问题内容: 在遍历列表时,我想根据条件删除列表中的项。请参见下面的代码。 这给了我一个例外。 如何才能做到这一点? 问题答案: 您需要使用和调用上,而不是使用循环。