开发者社区 问答 正文

Bukkit-检查玩家是否具有自定义物品/传递自定义物品对象有问题

我用自定义配方创建了自定义项目。我的主类方法:

@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')){

}

我不知道要在他的“项目”中加上什么。新项目栈还是其他?这些方法位于两个单独的文件中。

展开
收起
几许相思几点泪 2019-12-08 21:52:52 685 分享 版权
阿里云 AI 助理回答

在您的代码中,您创建了一个自定义物品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哪怕只有一个该物品。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答地址: