Reputation:
I created custom item with a custom recipe. My main class method:
@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);
}
Now, in other class I want to check if player has this my new item in the inventory
if(player.getInventory().contains('item')){
}
I don't know what to put in his 'item'. New itemstack or something else? These method are in two seperate files.
Upvotes: 0
Views: 2940
Reputation:
The Inventory class offers many useful methods, one of them being contains(ItemStack) that returns whether a player has a specific itemstack.
The issue now is how do we get our custom itemstack? Currently you create it locally inside the onEnable()
method, we need to declare it a field so we can access it throughout the class. To give access for outside classes globally, we either need to declare the lifecrystal
as public
or make a getter, I choose the latter since outside classes does not need to edit our custom item.
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;
}
Then in the second class:
public void anotherMethod() {
// we can now access lifecrystal
if(player.getInventory().contains(firstClass.getLifeCrystal())){
// do stuff
}
}
The firstClass
being a reference to your first class, that you should be able to set up on your own, but feel free to ask questions!
I highly recommend reading about visibility of variables, access and encapsulation. It's a great tool in programming that you will use more than this time. Simpletons are useful as well in some scenarios.
Upvotes: 1