Solved Is there a way to check for custom item name?

Discussion in 'Spigot Plugin Development' started by flashpoint, Jan 8, 2020.

  1. Hey there,

    I am working on changing color of leather if a player passed a cretin threads hold of an if statement, so far it works pretty well.

    I was wondering if its possible to check if the player is wearing Armour leather (leggings for now) AND if that Armour has a custom item name.

    So basically, I made a custom recipe for leather leggings and it works I've also assigned it its own named.
    This is what I am doing right now:


    if (player.getInventory().getLeggings() != null && player.getInventory().getLeggings().getType() == Material.LEATHER_LEGGINGS) {
    player.getInventory().setLeggings(getColorArmor(Material.LEATHER_LEGGINGS, c));
    }
    ((this is not the whole code))

    so basically I was wondering if its possible to do that and do something like:

    if (player.getInventory().getLeggings() != null && player.getInventory().getLeggings().getType() == Material.LEATHER_LEGGINGS) && getItemCustomNam.equls("Custom name")) {[
    bla bla bla...
    }


    Thank you for your time and assistance!
     
  2. Yes. What you are looking for is the ItemMeta.
    From the ItemMeta you can get the name, the lore, all the enchantments on the item etc.
    the method is ItemStack#getItemMeta(). It returns an ItemMeta object.
    From there you can call getName() and check it with equals.

    PS here is some advice to make your code more readable.
    Istead of calling the getter over and over again you should cache the result in a variable.

    Instead of
    Code (Java):
        if (player.getInventory().getLeggings() != null && player.getInventory().getLeggings().getType() == Material.LEATHER_LEGGINGS) {
          player.getInventory().setLeggings(getColorArmor(Material.LEATHER_LEGGINGS, c));
        }

    You can write
    Code (Java):
        PlayerInventory inventory = player.getInventory();
        ItemStack leggins = inventory.getLeggings();

        if (leggins != null && leggins.getType() == Material.LEATHER_LEGGINGS) {
          inventory.setLeggings(getColorArmor(Material.LEATHER_LEGGINGS, c));
        }
    This way you can re-use the inventory and the leggins in further calls.
     
    • Like Like x 1
  3. Thank you! :)