Fix NullPointer when changing equipment before checking attributes

This commit is contained in:
GreatWyrm 2024-07-10 23:46:43 -07:00 committed by iam
parent 2be6f9c507
commit 79716ab749
2 changed files with 20 additions and 2 deletions

View File

@ -224,7 +224,7 @@ public class LivingEntity extends Entity implements EquipmentHandler {
for (AttributeList.Modifier modifier : oldAttributes.modifiers()) {
// If the modifier currently modifies the slot we are updating
if (modifier.slot().contains(slot)) {
AttributeInstance attributeInstance = attributeModifiers.get(modifier.attribute().name());
AttributeInstance attributeInstance = getAttribute(modifier.attribute());
attributeInstance.removeModifier(modifier.modifier().id());
}
}
@ -235,7 +235,7 @@ public class LivingEntity extends Entity implements EquipmentHandler {
for (AttributeList.Modifier modifier : newAttributes.modifiers()) {
// If the modifier currently modifies the slot we are updating
if (modifier.slot().contains(slot)) {
AttributeInstance attributeInstance = attributeModifiers.get(modifier.attribute().name());
AttributeInstance attributeInstance = getAttribute(modifier.attribute());
attributeInstance.addModifier(modifier.modifier());
}
}

View File

@ -72,4 +72,22 @@ public class EntityAttributeTest {
player.setItemInMainHand(ItemStack.AIR);
assertEquals(0, Double.compare(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(), baseHealth));
}
@Test
public void testDirectlyAddAttributes(Env env) {
var instance = env.createFlatInstance();
var connection = env.createConnection();
var player = connection.connect(instance, new Pos(0, 42, 1)).join();
double baseHealth = 20;
double addition = 10;
// Don't compare against base health first (that will initialize the attribute, and we want to make sure we don't error when we add an item with attribute modifiers)
ItemStack itemStack = ItemStack.builder(Material.DIAMOND).set(ItemComponent.ATTRIBUTE_MODIFIERS,
new AttributeList(new AttributeList.Modifier(Attribute.GENERIC_MAX_HEALTH,
new AttributeModifier(NamespaceID.from("minestom:health"), addition, AttributeOperation.ADD_VALUE), EquipmentSlotGroup.MAIN_HAND))).build();
player.setItemInMainHand(itemStack);
assertEquals(0, Double.compare(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(), baseHealth + addition));
}
}