Skip to content

Using an Attribute

CleverNucleus edited this page Jun 22, 2021 · 2 revisions

Using an Attribute

Following on from the previous page, Adding an Attribute, we will look at how we would use Max Mana to do some things in-game. Before proceeding, there are some important things to note:

  • Our attribute's value is synced to the client every time it changes.
  • Our static access point to our attribute MAX_MANA is lazily loaded and is null on the client until the player has joined a world, and is null on the server until the datapack containing the jsons is loaded (obviously).

Accessing Max Mana

void genericMethod(PlayerEntity player) {
    // Cardinal Components data manager
    AttributeData data = ExAPI.DATA.get(player);
    
    // Max Mana's value
    double value = data.get(ExampleMod.MAX_MANA.get());
    
    // We can use this value however we want
    // Note that this value remains consistent across logical sides.
}

Modifying Max Mana

void genericMethod(PlayerEntity player) {
    // Cardinal Components data manager
    AttributeData data = ExAPI.DATA.get(player);
    
    // Adding 4.0 to Max Mana
    data.add(ExampleMod.MAX_MANA.get(), 4.0D);
    
    // Setting Max Mana to 4.0
    data.set(ExampleMod.MAX_MANA.get(), 4.0D);

    // Note that these both trigger Attribute Functions
}

Applying Modifiers to Max Mana

// UUID's should be statically initialised
static UUID MODIFIER = UUID.fromString("d540c322-cd52-46db-8251-65928971151b");

void genericMethod(PlayerEntity player) {
    // Cardinal Components data manager
    AttributeData data = ExAPI.DATA.get(player);
    
    // Creating the EntityAttributeModifier object
    EntityAttributeModifier modifier = new EntityAttributeModifier(MODIFIER, "examplemod.modifier.max_mana", 4.0D, Operation.ADDITION);
    
    // Applying the modifier to Max Mana
    data.applyAttributeModifier(ExampleMod.MAX_MANA.get(), modifier);
    
    // And if we want to remove it
    data.removeAttributeModifier(ExampleMod.MAX_MANA.get(), modifier);
    
    // Note that once the modifier is applied, the only way to remove it is through AttributeData#removeAttributeModifier
}

If you want to access an attribute that is present by default from PlayerEx, Minecraft or Reach-Entity-Attributes, use the following:

void genericMethod() {
    // Access to all Attribute instances implemented in the game
    IPlayerAttribute maxHealth = PlayerAttributes.MAX_HEALTH.get();
}

Please note that you should only use IAttribute#get in an ingame runtime method. Do not use this statically, or when a world instance does not exist (like trying to access the attribute in the main menu for some reason). This is because attributes are lazily loaded, and unless actually in game they will be null.