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

The Entity Attribute System - How to manipulate it in code


Recommended Posts

If you create a new entity, you may have stumbled across the Attribute System, for example if you want a custom max. health value.

Now a detailed explanation on what the Attribute System actually is can be found here: http://minecraft.gamepedia.com/Attribute

 

Here I will show you how to create your own Attributes for your entity and modify all of them in code.

 

NOTE: all attribute classes mentioned in this tutorial can be found in the package net.minecraft.entity.ai.attributes.

 

 

 

Create a new Attribute


Step 1:

To create a new attribute, you first need to create a new IAttribute instance (preferably static final in your entity registry class or somewhere). Now you don't need to make a new class which implements that interface!

Minecraft provides us with a standard class currently used for all its own Attributes called RangedAttribute. The constructor of that has the following parameters:

  • IAttribute parentIn - a parent attribute if available, can be null
  • String unlocalizedNameIn - the unlocalized name of the attribute. You can't add an attribute with the same name to an entity, so I usually precede the name with my Mod ID separated with a dot like TurretMod.MOD_ID + ".maxAmmoCapacity"
  • double defaultValue - the default value of the attribute. This value is set as base value when the entity is first created. It can't be lower than the minimum nor higher than the maximum value or else it will throw an IllegalArgumentException
  • double minimumValueIn - the minimum value of the attribute. This value is usually 0.0D. If the entity's attribute value falls below that, this value is used for it instead. It can't be bigger than the maximum value or else it will throw an IllegalArgumentException
  • double maximumValueIn - the maximum value of the attribute. This value is usually Double.MAX_VALUE. If the entity's attribute value falls above that, this value is used for it instead. It can't be smaller than the minimum value or else it will throw an IllegalArgumentException
     

Now at the end, my IAttribute instance variable looks like this:

public static final IAttribute MAX_AMMO_CAPACITY = new RangedAttribute(null, TurretMod.MOD_ID + ".maxAmmoCapacity", 256.0D, 0.0D, Double.MAX_VALUE);
 

But wait! If you want to share the attribute value and modifiers with the client, you'll need to call setShouldWatch(true) on that variable. The same way you can disable it, for whatever reason, with false instead of true as the parameter value. Conveniently it returns itself, so you can make a neat one-liner like this:

public static final IAttribute MAX_AMMO_CAPACITY = new RangedAttribute(null, TurretMod.MOD_ID + ".maxAmmoCapacity", 256.0D, 0.0D, Double.MAX_VALUE).setShouldWatch(true);

 

Step 2:

Great, now you have this useless variable the entity doesn't know about. To make it useful and working with the entity, you first need to register it to the entity's attribute list. To do so, override applyEntityAttributes()(if you've not already done so while changing the entity's max. health) and call this.getAttributeMap().registerAttribute(MY_OWN_ATTRIBUTE_VARIABLE), where MY_OWN_ATTRIBUTE_VARIABLE is firstly an overly long name, but more importantly your variable of your attribute instance created in Step 1. Here's an example from my mod:

    @Override
    protected void applyEntityAttributes() {
        super.applyEntityAttributes(); // Make sure to ALWAYS call the super method, or else max. health and other attributes from Minecraft aren't registered!!!

        this.getAttributeMap().registerAttribute(TurretAttributes.MAX_AMMO_CAPACITY);
    }
 

Step 3:

The attribute is now instanciated and registered, but how do I use its value? Simple! Just call this.getEntityAttribute(MY_OWN_ATTRIBUTE_VARIABLE).getAttributeValue(). It returns a double. If you want it to be an int, just use the MathHelper from Minecraft, for example MathHelper.ceiling_double_int(doubleVal)

 

 

 

Modify an Attribute


Now, to modify an attribute, there are 2 ways of doing so:

1. modify its base value

This is simple and straight forward, and as mentioned 2 times here so far, you may have already done this via the entity's max. health attribute. But to be complete, here's how you change the base value of an attribute with the example on the max. health:

this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(40.0D); //sets the entity max. health to 40 HP (20 hearts)
 

Please note: this does NOT get synched with the client! If you need to edit the base value, make sure you use packets if you want it to be shared (or change it on both sides). Otherwise use modifiers!

 

2. add modifiers to the attribute

This is a "reversable" way of changing the attribute value w/o messing with the base value. What we will do here is essentally this: http://minecraft.gamepedia.com/Attribute#Modifiers

That said, much like the Attribute Instance, we need to create our own AttributeModifier instance variable. Conveniently, there is already a class for us to use called AttributeModifier. It's constructor parameters are as follows:

  • UUID idIn - the UUID of this modifier, much like the Attribute name, this needs to be unique per Attribute. I usually give it a pre-defined, hardcoded Ver. 4 UUID via UUID.fromString("MY-UUID"), which was generated on this site. Mine looks like this:
    UUID.fromString("e6107045-134f-4c54-a645-75c3ae5c7a27")
     
  • String nameIn - the Modifier name, can be anything except empty, preferably readable and unique for the Attribute. Since the "uniqueness" of the modifier is already defined in the UUID, you can have duplicate names.
  • double amountIn - the Modifier value, can be anything. Note that the attribute, as prevously explained, has a min/max value and it can't get past that!
  • int operationIn - the Operation of the Modifier (careful, magic numbers over here!). Have a direct quote from the Minecraft Wiki:
    Quote
    The mathematical behavior is as follows:
        Operation 0: Increment X by Amount
        Operation 1: Increment Y by X * Amount,
        Operation 2: Y = Y * (1 + Amount) (equivalent to Increment Y by Y * Amount).
    The game first sets X = Base, then executes all Operation 0 modifiers, then sets Y = X, then executes all Operation 1 modifiers, and finally executes all Operation 2 modifiers.
    Brief explanation: Operation number is the value you feed the parameter.
    I also made an enum for it complete with javadoc for you to copy (with credits of course) if you want: https://github.com/SanAndreasP/SAPManagerPack/blob/master/java/de/sanandrew/core/manpack/util/EnumAttrModifierOperation.java

 

Now I've covered the parameters, it's time to make a new instance like this:

MY_CUSTOM_MODIFIER = new AttributeModifier(UUID.fromString("e6107045-134f-4c54-a645-75c3ae5c7a27"), "myCustomModifier420BlazeIt", 0.360D, EnumAttrModifierOperation.ADD_PERC_VAL_TO_SUM.ordinal());

 

You have the new modifier instance, but what do do with it? You can add or remove modifiers from an attribute like this (method names are self-explanatory):

entity.getEntityAttribute(MY_ATTRIBUTE_INSTANCE).applyModifier(MY_CUSTOM_MODIFIER);
entity.getEntityAttribute(MY_ATTRIBUTE_INSTANCE).removeModifier(MY_CUSTOM_MODIFIER);
 

Alright, you know now everything there is to know about attributes... wait, there's one more thing: attributes are saved and loaded automatically by the entity, no need to do that manually! Just make sure the client knows about the Attribute (register it properly as I've shown).

Edited by SanAndreasP
  • Like 3

Don't ask for support per PM! They'll get ignored! | If a post helped you, click the "Thank You" button at the top right corner of said post! |

mah twitter

This thread makes me sad because people just post copy-paste-ready code when it's obvious that the OP has little to no programming experience. This is not how learning works.

Link to comment
Share on other sites

Updated tutorial, because: After experimenting with attributes for awhile I noticed that Attributes in on themselves don't get send to the client automatically. So I looked for the cause of this, because the netcode actually was there, and found out you need to call

setShouldWatch(boolean)

after initializing.

Added this to Step 1 of the Create a new Attribute part.

Don't ask for support per PM! They'll get ignored! | If a post helped you, click the "Thank You" button at the top right corner of said post! |

mah twitter

This thread makes me sad because people just post copy-paste-ready code when it's obvious that the OP has little to no programming experience. This is not how learning works.

Link to comment
Share on other sites

I've updated the tutorial to accommodate for 1.10/1.11 and also fix formatting that broke due to the new forum software migration.

  • Like 1

Don't ask for support per PM! They'll get ignored! | If a post helped you, click the "Thank You" button at the top right corner of said post! |

mah twitter

This thread makes me sad because people just post copy-paste-ready code when it's obvious that the OP has little to no programming experience. This is not how learning works.

Link to comment
Share on other sites

  • 3 months later...
  • 1 year later...

Currently adding a custom set of attributes to all LivingEntityBase for my Dynamic Stealth mod (ie. adding a custom attribute to vanilla / unknown mod entities).  Had some trouble before I found a usable event for doing so, but I believe it's working now, so figured I'd chime in:

The event for doing such a thing (by which I mean, the ONLY event that works, when the entity is reloaded from disk, afaik) is 

EntityEvent.EntityConstructing

 

If there is another event with the correct timing, I do not know of it.  the join world event is too late to add attributes to the attribute map without warning spam in the server log.

Hopefully someone finds this useful

  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

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



×
×
  • Create New...

Important Information

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