gpt4 book ai didi

java - Bukkit 从库存中移除元素

转载 作者:行者123 更新时间:2023-11-30 08:55:50 26 4
gpt4 key购买 nike

我正在尝试检查玩家的库存中是否有元素,如果有则移除其中一个。这是我现在拥有的:

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

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

如何从玩家的元素栏中移除一件元素?

最佳答案

如果您只想移除一件元素,您可以遍历玩家库存中的元素,然后检查 Material 是否符合您的要求。如果是这样,您可以从 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;
}
}

关于java - Bukkit 从库存中移除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28870568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com