Search code examples
if-statementminecraftbukkit

Trouble detecting item used


I am trying to check if the item the player used is the custom item I added but for some reason it is not detecting the item. Here is the code.

@EventHandler
public void damage(EntityDamageByEntityEvent event){
    if(event.getEntity() instanceof Player && event.getDamager() instanceof Player){
        if(((Player) event.getDamager()).getInventory().getItemInMainHand() == CustomItems.potator()){
            System.out.println("potato");
        }
        else{
            //When i looked @ console this logged the same exact thing
            System.out.println("Damager Main Item = " + ((Player) event.getDamager()).getInventory().getItemInMainHand());
            System.out.println("Potator Item = " + CustomItems.potator());
        }
    }
}

Custom Item Class:

public static ItemStack potator(){

    ArrayList<String> lore = new ArrayList<String>();
    lore.add(ChatColor.GOLD + "Turns a random slot in the hotbar to a potato.");
    lore.add(ChatColor.GRAY + "1/100% chance from dropping from a potato.");

    ItemStack item = new ItemStack(Material.STONE_HOE);
    ItemMeta meta = item.getItemMeta();
    meta.setDisplayName(ChatColor.GOLD + "The Potator");
    meta.setLore(lore);
    item.setItemMeta(meta);
    return item;
}

Solution

  • if(((Player) event.getDamager()).getInventory().getItemInMainHand() == CustomItems.potator())
    

    In this line, by using ==, you're checking if the left and right-hand references are the same. You want to do content comparison, e.g. using .equals(). There's a good explanation of the differences on GeeksForGeeks.

    Spigot provides a stack size independent method isSimilar() which would be better than .equals().

    However, this would likely make your code execute for any stone hoe so you'll need to do your own checks. I would do something like this:

    public boolean isPotator(ItemStack i){
        if(i == null || !i.hasItemMeta())
            return false;
        ItemMeta meta = i.getItemMeta();
        if(!meta.hasDisplayName() || !meta.hasLore())
            return false;
        return meta.getDisplayName().equals(ChatColor.GOLD + "The Potator");
    }
    

    And then perform your check like so:

    @EventHandler
    public void damage(EntityDamageByEntityEvent event)
    {
        if(!(event.getEntity() instanceof Player && event.getDamager() instanceof Player))
            return;
        Player damager = (Player) event.getDamager();
        if(!isPotator(damager.getInventory().getItemInMainHand()))
            return;
        System.out.println("potato");
    }
    

    Since you have a CustomItem class, you can better this code by making a final string for the item name, which you can then use in both the ItemStack creation and the isPotator check.