In this lesson, you will learn how to use the PreAttributeChange function to enforce strict boundaries on your character’s attributes, ensuring they never exceed their intended range.
Why Clamp Attributes?
When you use the Gameplay Ability System (GAS), attributes like Health or Stamina are often modified by various Gameplay Effects. Without intervention, a "Heal" effect might push your Health far beyond your MaxHealth. While you could manually check this every time an effect is applied, PreAttributeChange provides a centralized, robust location to intercept these changes automatically before the attribute is officially updated.
Implementing PreAttributeChange
The PreAttributeChange function is a member of your UAttributeSet class. It triggers whenever an attribute is about to change, providing you with the Attribute being modified and the NewValue it is attempting to reach.
Here is how you implement it to clamp Health against MaxHealth:
void UMyAttributeSet::PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue)
{
Super::PreAttributeChange(Attribute, NewValue);
if (Attribute == GetHealthAttribute())
{
// Clamp the NewValue between 0 and the current MaxHealth
NewValue = FMath::Clamp(NewValue, 0.0f, GetMaxHealth());
}
}
How It Works
- The Check: We first verify if the
Attributebeing modified is indeedHealthby comparing it againstGetHealthAttribute(). - The Clamp: We use
FMath::Clampto constrainNewValue. If the incoming value is higher thanGetMaxHealth(), it is forced down to the maximum. If it is negative, it is forced up to zero. - The Pass-by-Reference: Because
NewValueis passed by reference, any modification you make to it inside this function will be the final value applied to the attribute.
By placing this logic in your AttributeSet, you ensure that no matter how complex your Gameplay Effects become, your attributes remain within the logical constraints defined by your game design.
Key Takeaway: Use PreAttributeChange in your AttributeSet to intercept and clamp attribute values before they are applied, guaranteeing your character stats never violate your design boundaries.