Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[1.16.5] Attribute Modifiers With Duplicate Items [Solved]


urbanxx001
 Share

Recommended Posts

From this post, I've modified the original armor attribute of my custom item. The biggest change between that post and now is that the attribute multimap is immutable, so it needs to be copied to a mutable map, adjusted, and then copied to an immutable one again. Normally it would be easier to create a new armor material, however the value I need depends on a variable (extraArmor) in the item class. The armor value changes correctly, but only when one instance of the item is present in the inventory. If another one is there, then the armor of the newest instance overwrites the previous item(s). I've tired alternatives such as adding a new armor modifier (Attempt 2) or using an ItemAttributeModifierEvent instead of getAttributeModifiers, but they all face the same problem. I'm not sure why they would change since the extraArmor value isn't static and isn't called or updated statically as far as I'm aware. If anyone can help I'd be grateful.

Attempt 1: Edit original values

Spoiler


	public static<K, V> ListMultimap<K, V> toMutableMultimap(Multimap<K, V> original) {
		ListMultimap<K, V> copy = ArrayListMultimap.create();
		copy.putAll(original);
		return copy;
	}

	public static<K, V> ImmutableMultimap<K, V> toImmutableMultimap(ListMultimap<K, V> original) {
		return new ImmutableMultimap.Builder<K, V>().putAll(original).build();
	}

	@Override
	public Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlotType slot, ItemStack stack) {
		Multimap<Attribute, AttributeModifier> multimap = super.getAttributeModifiers(slot, stack);
		ListMultimap<Attribute, AttributeModifier> mutableMultimap = toMutableMultimap(multimap);
		final Collection<AttributeModifier> modifiers = mutableMultimap.get(Attributes.ARMOR);
      
		Item item = stack.getItem();
		if (item instanceof MyItem && slot == this.slot) {
			ArmorItem armorItem = (ArmorItem) item;
			MyItem myItem = (MyItem) item;

			UUID[] uuid_arr = ObfuscationReflectionHelper.getPrivateValue(ArmorItem.class, armorItem, "ARMOR_MODIFIER_UUID_PER_SLOT");
			if (uuid_arr != null) {
				UUID uuid = uuid_arr[slot.getIndex()];
				this.replaceModifier(mutableMultimap, Attributes.ARMOR, uuid, myItem.extraArmor);
			}
		}
		return toImmutableMultimap(mutableMultimap);
	}

	private void replaceModifier(ListMultimap<Attribute, AttributeModifier> multimap, Attribute attribute, UUID id, double newValue) {
		final Collection<AttributeModifier> modifiers = multimap.get(attribute);
		final Optional<AttributeModifier> modifierOptional = 
      modifiers.stream().filter(attributeModifier -> attributeModifier.getId().equals(id)).findFirst();

		if (modifierOptional.isPresent()) {
			final AttributeModifier modifier = modifierOptional.get();
			modifiers.remove(modifier);
			modifiers.add(new AttributeModifier(modifier.getId(), modifier.getName(), modifier.getAmount() + newValue, 	modifier.getOperation()));
		}
	}

 

 

Attempt 2: Add unique modifier

Spoiler


	public static UUID MY_ITEM_ARMOR_UUID = UUID.fromString("b5ba8c15-4e13-437b-9d3a-d80f2849362f");
	public AttributeModifier MY_ITEM_ARMOR_MODIFIER = new AttributeModifier(MY_ITEM_ARMOR_UUID, "My item armor modifier", this.extraArmor, AttributeModifier.Operation.ADDITION);

	@Override
	public Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlotType slot, ItemStack stack) {
		Multimap<Attribute, AttributeModifier> multimap = super.getAttributeModifiers(slot, stack);
		ListMultimap<Attribute, AttributeModifier> mutableMultimap = toMutableMultimap(multimap);
		final Collection<AttributeModifier> modifiers = mutableMultimap.get(Attributes.ARMOR);
      
		final Optional<AttributeModifier> modifierOptional = modifiers.stream()
      	.filter(attributeModifier -> attributeModifier.getId().equals(MY_ITEM_ARMOR_UUID)).findFirst();

		if (!modifierOptional.isPresent() && item instanceof MyItem && slot == this.slot) {
			modifiers.add(MY_ITEM_ARMOR_MODIFIER);
		}
		return toImmutableMultimap(mutableMultimap);
	}

 

 

Edited by urbanxx001
Link to comment
Share on other sites

Here's the class for attempt 1. For attempt 2 I've also tried assigning random UUID's and/or random modifier names for each item instance, but they still remain linked.

Spoiler



package com.author.my_mod.group.items;

import com.google.common.collect.*;
import net.minecraft.entity.ai.attributes.*;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.*;
import net.minecraft.util.*;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;

import java.util.*;

public class MyItem extends ArmorItem {
	private final EquipmentSlotType slot;
	public int extraArmor = 0;

	public MyItem(IArmorMaterial material, EquipmentSlotType slot, Properties properties) {
		super(material, slot, properties);
		this.slot = slot;
	}

	public static<K, V> ListMultimap<K, V> toMutableMultimap(Multimap<K, V> original) {
		ListMultimap<K, V> copy = ArrayListMultimap.create();
		copy.putAll(original);
		return copy;
	}

	public static<K, V> ImmutableMultimap<K, V> toImmutableMultimap(ListMultimap<K, V> original) {
		return new ImmutableMultimap.Builder<K, V>().putAll(original).build();
	}

	@Override
	public Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlotType slot, ItemStack stack) {
		Multimap<Attribute, AttributeModifier> multimap = super.getAttributeModifiers(slot, stack);
		ListMultimap<Attribute, AttributeModifier> mutableMultimap = toMutableMultimap(multimap);

		Item item = stack.getItem();
		if (item instanceof MyItem && slot == this.slot) {
			UUID[] uuid_arr = ObfuscationReflectionHelper.getPrivateValue(ArmorItem.class, (ArmorItem) item, "ARMOR_MODIFIER_UUID_PER_SLOT");
			if (uuid_arr != null) {
				MyItem myItem = (MyItem) item;
				UUID uuid = uuid_arr[slot.getIndex()];
				this.replaceModifier(mutableMultimap, Attributes.ARMOR, uuid, myItem.extraArmor);
			}
		}
		return toImmutableMultimap(mutableMultimap);
	}

	private void replaceModifier(ListMultimap<Attribute, AttributeModifier> multimap, Attribute attribute, UUID id, double newValue) {
		final Collection<AttributeModifier> modifiers = multimap.get(attribute);
		final Optional<AttributeModifier> modifierOptional = modifiers.stream().filter(attributeModifier -> attributeModifier.getId().equals(id)).findFirst();

		if (modifierOptional.isPresent()) {
			final AttributeModifier modifier = modifierOptional.get();
			modifiers.remove(modifier);
			modifiers.add(new AttributeModifier(modifier.getId(), modifier.getName(), modifier.getAmount() + newValue, modifier.getOperation()));
		}
	}

	@Override
	public ActionResult<ItemStack> use(World world, PlayerEntity player, Hand hand) {
		final ItemStack stack = player.getItemInHand(hand);
		if (!world.isClientSide()) {
			this.extraArmor++;
			if (this.extraArmor > 3) {
				this.extraArmor = 0;
			}
		}
		return new ActionResult<>(ActionResultType.CONSUME, stack);
	}

}

 

 

Edited by urbanxx001
Link to comment
Share on other sites

2 minutes ago, urbanxx001 said:

Here's the class

You can't really have an instance field like extraArmor in item classes, since items are singleton and every stack will share the same item. This means that for example if one player uses the item and changes the extraArmor field, it will also change for all other players that also have that item.

  • Thanks 1
Link to comment
Share on other sites

1 minute ago, vemerion said:

You can't really have an instance field like extraArmor in item classes, since items are singleton and every stack will share the same item. This means that for example if one player uses the item and changes the extraArmor field, it will also change for all other players that also have that item.

Ah ok. So I should store it in NBT instead?

Link to comment
Share on other sites

  • urbanxx001 changed the title to [1.16.5] Attribute Modifiers With Duplicate Items [Solved]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share



  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • okay thank you for clarifying! I'll try to implement the setup method and event listeners as an extra class, maybe this works!
    • Show your code. You do not have to draw the entire texture (see above). You do not have to draw the texture at 1:1 scale.
    • MC version :1.16.5 Forge version :36.2.20 I added "MeleeAttackGoal" in my entity,and then I can‘t summon this entity.what's wrong in my code? //the entity's code package net.fsmc.classmates.animals; import net.minecraft.entity.AgeableEntity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.ai.attributes.Attributes; import net.minecraft.entity.ai.goal.*; import net.minecraft.entity.merchant.villager.AbstractVillagerEntity; import net.minecraft.entity.monster.ZombifiedPiglinEntity; import net.minecraft.entity.passive.AnimalEntity; import net.minecraft.entity.passive.IronGolemEntity; import net.minecraft.entity.passive.TurtleEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.world.World; import net.minecraft.world.server.ServerWorld; import javax.annotation.Nullable; public class n7Yjy extends AnimalEntity  {          public n7Yjy(EntityType<? extends AnimalEntity> type, World worldIn) {         super(type, worldIn);     }          public static AttributeModifierMap.@NotNull MutableAttribute registerAttributes() {          return MobEntity.func_233666_p_()                  .createMutableAttribute(Attributes.MOVEMENT_SPEED, 0.23000000417232513D)                  .createMutableAttribute(Attributes.ATTACK_DAMAGE, 7.0D)                  .createMutableAttribute(Attributes.FOLLOW_RANGE, 40.0D)                  .createMutableAttribute(Attributes.MAX_HEALTH, 30.0D);      }          @Override     protected void registerGoals(){         this.goalSelector.addGoal(2, new RandomWalkingGoal(this , 1D,1));         this.goalSelector.addGoal(3, new LookAtGoal(this,PlayerEntity.class,8.0f));         this.goalSelector.addGoal(3,new MeleeAttackGoal(this,0.3,true));         this.Target();     }     public void Target(){         this.targetSelector.addGoal(2, (new HurtByTargetGoal(this,new Class[0])).setCallsForHelp(new Class[]{ZombifiedPiglinEntity.class}));         this.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(this, PlayerEntity.class, true));         this.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(this, AbstractVillagerEntity.class, false));         this.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(this, IronGolemEntity.class, true));         this.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(this, TurtleEntity.class, 10, true, false, TurtleEntity.TARGET_DRY_BABY));     }     @Nullable     @Override     public AgeableEntity createChild(ServerWorld serverWorld, AgeableEntity ageableEntity) {         return null;     } }
    • I am trying to set up my first project and it says this: Unsupported Java.  Your build is currently configured to use Java 16.0.1 and Gradle 6.8.1. Possible solution:  - Use Java 15 as Gradle JVM: Open Gradle settings   - Upgrade Gradle wrapper to 7.0 version and re-import the project I know I am using Java 15 already because in the gradle settings it says gradle JVM: 15 version 15.0.2 So my question is how do I upgrade the gradle wrapper? Sorry if this is a noobie question, trying to set up my first project.  
    • Yes, I don't think you want this as a mod jar. I am not 100% on the details, but ModLauncher implements a multi-module-layer system and you need to load into a specific layer.
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.