Search code examples
javaminecraftspigot

Ignore UUIDs in attribute modifiers when comparing items


When I try to find, if two items are same, I can't. It's because of a attribute modifiers that have some UUIDs that are always random so I can't compare items with attribute modifiers. Even though I know I can compare items by name etc. I want to ask, if there is some way to do it with attribute modifiers.

public static Object item() {
    ItemStack item = new ItemStack(Material.STICK);
    ItemMeta meta = item.getItemMeta();

    meta.setDisplayName("§2§lCool sword");
    meta.addAttributeModifier(Attribute.GENERIC_ATTACK_DAMAGE, new AttributeModifier("generic.attackDamage", 11.0, AttributeModifier.Operation.ADD_NUMBER));
    meta.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED, new AttributeModifier("generic.attackSpeed", 1.4, AttributeModifier.Operation.ADD_NUMBER));
    meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
    item.setItemMeta(meta);

    return item;
}

public static void processEvent(Entity damager, LivingEntity entity) {
    if (!(damager instanceof Player)) return;
    Player player = (Player) damager;

    if (!player.getItemInHand().isSimilar((ItemStack) item())) return;

    entity.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING,200, 1, true, false));
}

Solution

  • If there is only attributes that are creating issue, you can remove them from both item, then check. If there is other things, you can write your own method that check for type, displayname, lore etc...

    To check without attribute:

    1. Copy both item
    2. Remove attribute
    3. Use item.isSimilar(other)

    Example:

    public static boolean areSimilar(ItemStack item, ItemStack other) {
        // setup first item
        item = item.clone();
        item.getAttributeModifiers().clear();
        // setup second item
        other = other.clone();
        other.getAttributeModifiers().clear();
        return item.isSimilar(other);
    }
    

    PS: I suggest you to return ItemStack instead of Object in your item()'s method.