我用自定义配方创建了自定义项目。我的主类方法:
@Override
public void onEnable() {
// Life Crystal
ItemStack lifecrystal = new ItemStack(Material.DIAMOND);
ItemMeta meta = lifecrystal.getItemMeta();
meta.setDisplayName(ChatColor.GOLD + "Life Crystal");
ArrayList<String> lores = new ArrayList<>();
lores.add("Increase your life points...");
lores.add("...or just revive someone");
meta.setLore(lores);
lifecrystal.setItemMeta(meta);
NamespacedKey key = new NamespacedKey(this, "life_crystal");
ShapedRecipe recipe = new ShapedRecipe(key, lifecrystal);
recipe.shape(" E ", "LGL", "DID");
recipe.setIngredient('E', Material.EMERALD);
recipe.setIngredient('L', Material.LAPIS_LAZULI);
recipe.setIngredient('G', Material.GOLDEN_APPLE);
recipe.setIngredient('D', Material.DIAMOND);
recipe.setIngredient('I', Material.GOLD_INGOT);
Bukkit.addRecipe(recipe);
}
现在,在其他课程中,我想检查玩家是否在库存中有我的新物品
if(player.getInventory().contains('item')){
}
我不知道要在他的“项目”中加上什么。新项目栈还是其他?这些方法位于两个单独的文件中。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在您的代码中,您创建了一个自定义物品Life Crystal
。为了检查玩家的库存中是否包含这个特定的物品,您需要使用该物品的Material
类型或者更准确地,是它的ItemStack
实例来完成匹配。由于您还为物品设置了自定义的NamespacedKey
,理论上可以通过这个键来精确查找,但在大多数情况下直接比较ItemStack
更为常见。
您已经知道物品的基础材料是Material.DIAMOND
,但因为您添加了自定义的lore和display name,最准确的方法是创建一个与lifecrystal
相同的ItemStack
实例用于比较。这样可以确保即使有其他附魔或修改过的钻石也能正确识别出您的特殊物品。
示例代码如下:
// 在方法内
ItemStack lifeCrystalCheck = new ItemStack(Material.DIAMOND);
ItemMeta checkMeta = lifeCrystalCheck.getItemMeta();
// 确保复制了之前设置的所有属性,包括DisplayName和Lore
if (checkMeta != null) {
checkMeta.setDisplayName(ChatColor.GOLD + "Life Crystal");
ArrayList<String> lores = new ArrayList<>();
lores.add("Increase your life points...");
lores.add("...or just revive someone");
checkMeta.setLore(lores);
lifeCrystalCheck.setItemMeta(checkMeta);
}
// 现在您可以使用这个itemStack进行精确匹配
if(player.getInventory().containsAtLeast(lifeCrystalCheck, 1)) {
// 玩家至少有一个"Life Crystal"在他们的库存中
}
请注意,我使用了containsAtLeast
方法,它不仅检查物品是否存在,还检查至少存在一个的数量。如果您只需要确认是否存在,不关心数量,这种方法也是适用的,因为它会返回true哪怕只有一个该物品。