TExcelTAD
Home › Unreal Engine 5 with C++ › GAS: Attributes & Effects

GAS: Attributes & Effects

The Gameplay Ability System (GAS, plugin Gameplay Abilities) is Unreal's framework for abilities, buffs, damage and stats. Fortnite, Lyra and many shipped games are built on it. It has a learning curve, but it solves problems every action game has: stacking buffs, cooldowns, costs, networked prediction, and designers creating new effects without code.

The pieces:

Piece What it is
UAbilitySystemComponent (ASC) the component that owns attributes, active effects, granted abilities and tags
UAttributeSet a class holding FGameplayAttributeData values: Health, MaxHealth, Mana, MoveSpeed…
Gameplay Effect (UGameplayEffect, a data asset/Blueprint) a rule that changes attributes and tags: instant damage, a 5 s burn, a permanent +10 armor
Gameplay Ability (UGameplayAbility) an action: attack, dash, heal (next lesson)
Gameplay Cue cosmetic response (sound, particles), triggered by tags under GameplayCue.*, replicated cheaply

Add "GameplayAbilities", "GameplayTags" and "GameplayTasks" to Build.cs, and enable the Gameplay Abilities plugin.

An attribute set

cpp
// ArenaAttributeSet.h
#pragma once

#include "CoreMinimal.h"
#include "AttributeSet.h"
#include "AbilitySystemComponent.h"
#include "ArenaAttributeSet.generated.h"

UCLASS()
class ARENA_API UArenaAttributeSet : public UAttributeSet
{
    GENERATED_BODY()

public:
    UPROPERTY(BlueprintReadOnly, Category = "Attributes", ReplicatedUsing = OnRep_Health)
    FGameplayAttributeData Health;
    GAMEPLAYATTRIBUTE_PROPERTY_GETTER(UArenaAttributeSet, Health);
    GAMEPLAYATTRIBUTE_VALUE_GETTER(Health);
    GAMEPLAYATTRIBUTE_VALUE_SETTER(Health);
    GAMEPLAYATTRIBUTE_VALUE_INITTER(Health);

    UPROPERTY(BlueprintReadOnly, Category = "Attributes", ReplicatedUsing = OnRep_MaxHealth)
    FGameplayAttributeData MaxHealth;
    GAMEPLAYATTRIBUTE_PROPERTY_GETTER(UArenaAttributeSet, MaxHealth);
    GAMEPLAYATTRIBUTE_VALUE_GETTER(MaxHealth);
    GAMEPLAYATTRIBUTE_VALUE_SETTER(MaxHealth);
    GAMEPLAYATTRIBUTE_VALUE_INITTER(MaxHealth);

    // A "meta" attribute: not replicated, only a channel for incoming damage.
    UPROPERTY(BlueprintReadOnly, Category = "Attributes")
    FGameplayAttributeData IncomingDamage;
    GAMEPLAYATTRIBUTE_PROPERTY_GETTER(UArenaAttributeSet, IncomingDamage);
    GAMEPLAYATTRIBUTE_VALUE_GETTER(IncomingDamage);
    GAMEPLAYATTRIBUTE_VALUE_SETTER(IncomingDamage);

    virtual void PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue) override;
    virtual void PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data) override;
    virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;

protected:
    UFUNCTION()
    void OnRep_Health(const FGameplayAttributeData& OldHealth);

    UFUNCTION()
    void OnRep_MaxHealth(const FGameplayAttributeData& OldMaxHealth);
};
cpp
// ArenaAttributeSet.cpp
#include "ArenaAttributeSet.h"
#include "GameplayEffectExtension.h"
#include "Net/UnrealNetwork.h"

void UArenaAttributeSet::PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue)
{
    Super::PreAttributeChange(Attribute, NewValue);
    if (Attribute == GetHealthAttribute())
    {
        NewValue = FMath::Clamp(NewValue, 0.f, GetMaxHealth());   // clamps the current value
    }
}

void UArenaAttributeSet::PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data)
{
    Super::PostGameplayEffectExecute(Data);
    if (Data.EvaluatedData.Attribute == GetIncomingDamageAttribute())
    {
        const float Damage = GetIncomingDamage();
        SetIncomingDamage(0.f);
        SetHealth(FMath::Clamp(GetHealth() - Damage, 0.f, GetMaxHealth()));   // base value of Health
        // here: broadcast "died" if Health reached 0, apply hit-react tags, etc.
    }
}

void UArenaAttributeSet::OnRep_Health(const FGameplayAttributeData& OldHealth)
{
    GAMEPLAYATTRIBUTE_REPNOTIFY(UArenaAttributeSet, Health, OldHealth);
}

void UArenaAttributeSet::OnRep_MaxHealth(const FGameplayAttributeData& OldMaxHealth)
{
    GAMEPLAYATTRIBUTE_REPNOTIFY(UArenaAttributeSet, MaxHealth, OldMaxHealth);
}

void UArenaAttributeSet::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);
    DOREPLIFETIME_CONDITION_NOTIFY(UArenaAttributeSet, Health, COND_None, REPNOTIFY_Always);
    DOREPLIFETIME_CONDITION_NOTIFY(UArenaAttributeSet, MaxHealth, COND_None, REPNOTIFY_Always);
}

Many projects wrap the four GAMEPLAYATTRIBUTE_* macros in one ATTRIBUTE_ACCESSORS(Class, Name) macro of their own; it's the same code.

Each attribute has a base value (changed permanently by instant effects) and a current value (base plus all active temporary modifiers). A 10-second +50 % speed buff changes only the current value; when it expires, the current value is recomputed from the base. PreAttributeChange sees current-value changes; PostGameplayEffectExecute runs after instant (base-changing) effects. That's why damage goes through a meta attribute processed there.

Gameplay effects

Effects are assets: Add → Blueprint Class → GameplayEffect, then configure in the details panel.

Setting Options
Duration Policy Instant (changes the base value once), Has Duration (temporary modifier), Infinite (until removed)
Modifiers attribute + operation (Add, Multiply, Divide, Override) + magnitude (a number, a curve table by level, an attribute-based value, or SetByCaller)
Period for duration effects: execute every N seconds (damage over time)
Stacking how repeated applications combine: aggregate by source or target, stack limit, duration refresh
Components (UE 5.3+) granted tags, application requirements, immunity, granted abilities… configured as GE Components
cpp
// Applying an effect from C++ with a SetByCaller magnitude
#include "AbilitySystemBlueprintLibrary.h"
#include "ArenaTags.h"

void AArenaCharacter::DealDamage(AActor* Target, float Amount)
{
    UAbilitySystemComponent* TargetASC = UAbilitySystemBlueprintLibrary::GetAbilitySystemComponent(Target);
    if (!TargetASC || !DamageEffectClass) return;

    FGameplayEffectContextHandle Context = AbilitySystem->MakeEffectContext();
    Context.AddSourceObject(this);
    FGameplayEffectSpecHandle Spec = AbilitySystem->MakeOutgoingSpec(DamageEffectClass, /*Level*/ 1.f, Context);
    if (Spec.IsValid())
    {
        Spec.Data->SetSetByCallerMagnitude(TAG_Data_Damage, Amount);   // GE_Damage: IncomingDamage Add SetByCaller(Data.Damage)
        AbilitySystem->ApplyGameplayEffectSpecToTarget(*Spec.Data.Get(), TargetASC);
    }
}

A runnable model of attributes and effects

The model keeps a base value and a list of active modifiers per attribute, recomputes the current value with GAS's default formula, (Base + ΣAdd) × (1 + Σ(Multiply − 1)) / Divide, with Override winning, and runs instant, duration and periodic effects over a few seconds of game time.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <map>
#include <string>
#include <vector>

enum class Op { Add, Multiply, Override };
struct Modifier { std::string Attr; Op Operation; double Magnitude; };
struct ActiveEffect { std::string Name; std::vector<Modifier> Mods; double Remaining, Period, NextTick; bool Periodic; };

struct ASC {
    std::map<std::string, double> Base;
    std::vector<ActiveEffect> Active;

    double Current(const std::string& attr) const {
        double add = 0, mulBias = 0;
        bool hasOverride = false; double overrideValue = 0;
        for (const auto& e : Active) {
            if (e.Periodic) continue;                         // periodic effects change the base when they tick
            for (const auto& m : e.Mods) {
                if (m.Attr != attr) continue;
                if (m.Operation == Op::Add) add += m.Magnitude;
                if (m.Operation == Op::Multiply) mulBias += m.Magnitude - 1;
                if (m.Operation == Op::Override) { hasOverride = true; overrideValue = m.Magnitude; }
            }
        }
        if (hasOverride) return overrideValue;
        return (Base.at(attr) + add) * (1 + mulBias);
    }

    void ExecuteInstant(const std::string& name, const std::vector<Modifier>& mods) {
        for (const auto& m : mods) {
            double& b = Base[m.Attr];
            if (m.Operation == Op::Add) b += m.Magnitude;
            if (m.Operation == Op::Multiply) b *= m.Magnitude;
            if (m.Attr == "Health") b = std::clamp(b, 0.0, Current("MaxHealth"));   // like PreAttributeChange
        }
        std::cout << "  " << name << " -> Health " << Base["Health"] << "\n";
    }

    void Tick(double dt) {
        for (auto& e : Active) {
            e.Remaining -= dt;
            if (e.Periodic) {
                e.NextTick -= dt;
                while (e.NextTick <= 1e-9 && e.Remaining > -1e-9) { ExecuteInstant(e.Name + " tick", e.Mods); e.NextTick += e.Period; }
            }
        }
        for (auto& e : Active) if (e.Remaining <= 1e-9) std::cout << "  " << e.Name << " expired\n";
        std::erase_if(Active, [](const ActiveEffect& e) { return e.Remaining <= 1e-9; });
    }
};

int main() {
    std::cout << std::fixed << std::setprecision(1);
    ASC asc;
    asc.Base = {{"Health", 100}, {"MaxHealth", 100}, {"MoveSpeed", 600}};

    std::cout << "t=0\n";
    asc.ExecuteInstant("GE_Damage (instant, 30)", {{"Health", Op::Add, -30}});
    asc.Active.push_back({"GE_Haste", {{"MoveSpeed", Op::Multiply, 1.5}}, 3, 0, 0, false});
    asc.Active.push_back({"GE_Sprint", {{"MoveSpeed", Op::Multiply, 1.5}}, 2, 0, 0, false});
    asc.Active.push_back({"GE_Burn", {{"Health", Op::Add, -5}}, 3, 1, 1, true});
    std::cout << "  MoveSpeed current " << asc.Current("MoveSpeed") << " (two x1.5 buffs: 600 x (1 + 0.5 + 0.5))\n";

    for (int t = 1; t <= 4; t++) {
        std::cout << "t=" << t << "\n";
        asc.Tick(1.0);
        std::cout << "  Health " << asc.Base["Health"] << ", MoveSpeed " << asc.Current("MoveSpeed") << "\n";
    }
    std::cout << "heal for 999\n";
    asc.ExecuteInstant("GE_Heal", {{"Health", Op::Add, 999}});
}
t=0
  GE_Damage (instant, 30) -> Health 70.0
  MoveSpeed current 1200.0 (two x1.5 buffs: 600 x (1 + 0.5 + 0.5))
t=1
  GE_Burn tick -> Health 65.0
  Health 65.0, MoveSpeed 1200.0
t=2
  GE_Burn tick -> Health 60.0
  GE_Sprint expired
  Health 60.0, MoveSpeed 900.0
t=3
  GE_Burn tick -> Health 55.0
  GE_Haste expired
  GE_Burn expired
  Health 55.0, MoveSpeed 600.0
t=4
  Health 55.0, MoveSpeed 600.0
heal for 999
  GE_Heal -> Health 100.0

Two details worth noticing. The two ×1.5 speed buffs gave ×2.0, not ×2.25: by default GAS adds multiplier bonuses (newer 5.x versions also offer compounding operations; check EGameplayModOp in yours). And the huge heal was clamped to MaxHealth, which is what the clamp in PreAttributeChange/PostGameplayEffectExecute is for.

Test yourself

What does an Instant gameplay effect change?

  1. Only the current value, temporarily
  2. The attribute's base value, permanently
  3. Only tags
  4. Nothing until it expires

Why route damage through a non-replicated 'IncomingDamage' meta attribute?

  1. It's required by the engine
  2. PostGameplayEffectExecute can apply armor, clamp and react (death) in one place before changing Health
  3. To save memory
  4. Meta attributes replicate faster

With GAS's default aggregation, two active Multiply 1.5 modifiers on MoveSpeed 600 give…

  1. 900
  2. 1200
  3. 1350
  4. 600