Course contentsShow
← Unreal Engine Game Development
Lesson 637 of 8809. Gameplay Ability System (GAS)Free lesson

Applying Clamping Logic in PreAttributeChange

Override the PreAttributeChange function to enforce boundaries on attributes like Health or Stamina to prevent values from exceeding maximum thresholds.

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

  1. The Check: We first verify if the Attribute being modified is indeed Health by comparing it against GetHealthAttribute().
  2. The Clamp: We use FMath::Clamp to constrain NewValue. If the incoming value is higher than GetMaxHealth(), it is forced down to the maximum. If it is negative, it is forced up to zero.
  3. The Pass-by-Reference: Because NewValue is 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.