我用自定义配方创建了自定义项目。我的主要课堂方法:
@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')){
}
我不知道要在“项目”中添加什么。新项目栈还是其他?这些方法位于两个单独的文件中。
答案 0 :(得分:1)
库存类提供了许多有用的方法,其中之一是contains(ItemStack),它返回玩家是否具有特定的物品堆栈。
现在的问题是如何获得自定义项目堆栈?当前,您可以在onEnable()
方法内部本地创建它,我们需要将其声明为一个字段,以便我们可以在整个类中对其进行访问。要全局访问外部类,我们需要将lifecrystal
声明为public
或进行一个getter,我选择后者是因为外部类不需要编辑我们的自定义项。
private ItemStack lifecrystal; // declare globally
@Override
public void onEnable() {
// initilize locally
lifecrystal = new ItemStack(Material.DIAMOND);
// rest of your itemstack code etc
}
// getter method for outside classes to access our itemstack
public ItemStack getLifeCrystal() {
return lifecrystal;
}
然后在第二堂课:
public void anotherMethod() {
// we can now access lifecrystal
if(player.getInventory().contains(firstClass.getLifeCrystal())){
// do stuff
}
}
firstClass
是对您的头等舱的指称,您应该可以自行设置,但是随时可以提出问题!
我强烈建议您阅读有关变量的可见性,访问和封装的信息。这是编程中的绝佳工具,您将不只使用这次。 在某些情况下,Simpleton也很有用。