Item enum problem - Only first item works.

Discussion in 'Spigot Plugin Development' started by Silvandre, May 7, 2017.

Thread Status:
Not open for further replies.
  1. Hello everyone! I've been coding with Java for around a year now (first year of university...), and I wanted to get in to plugin development as a way to improve my skills, doing something I enjoy, and for my own server!

    My problem is that I have an Enum of items, and whenever I do player.getInventory().addItem(ItemsEnum.COPPER_COIN.getItemStack()); it won't add anything to the player's inventory, (Same with SILVER_COIN and GOLD_COIN), however, if I do the same with POUCH, then it works just fine... I've read the oracle documentation on enums, google'd tutorials on enums, and searched for similar problems on the spigot forums.

    If I copy the enum code straight from the Enum, into the command I have, it does give the player the item.

    Code (Text):
    public enum ItemsEnum {
        POUCH(1, "Pouch", ""),
        GOLD_COIN(2, "Gold Coin", "Gold Coin worth 100 silver."),
        SILVER_COIN(3, "Silver Coin", "Silver Coin worth 100 copper."),
        COPPER_COIN(4, "Copper Coin", "The smallest coin.");

        private ItemStack item = null;

        ItemsEnum(int durability, String name, String lore){
            item = new ItemStack(Material.WOOD_HOE, 1, (short) durability);
            ItemMeta itemMeta = item.getItemMeta();
            itemMeta.setDisplayName(ChatColor.RESET + name);
            itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
            ArrayList<String> aux = new ArrayList<>();
            aux.add(lore);
            itemMeta.setLore(aux);
            item.setItemMeta(itemMeta);
        }

        public ItemStack getItemStack(){
            return this.item;
        }
    }
    There is no stack trace whenever I try to give the player any of the items that don't work.

    Thanks for the help!
     
  2. Replace this:
    with:
    Code (Text):

    public ItemStack getItemStack() {
        return this.item.clone();
    }
     
     
  3. Thank you so much! This works! Such a simple fix.

    Might I ask, why is it that this is necessary?

    Is it something along the lines of, by returning the item, it returns a reference to that specific item, instead of a new one, so it can only be given once?
     
    #3 Silvandre, May 7, 2017
    Last edited: May 7, 2017
  4. I don't exactly know, why this is so. Please mark this thread as solfed.
     
Thread Status:
Not open for further replies.