TExcelTAD
Home › Unreal Engine 5 with C++ › GAS: Abilities

GAS: Abilities

A Gameplay Ability is one thing an actor can do: a sword swing, a dash, a fireball, a heal. GAS gives every ability the same lifecycle: can activate? (tags, cost, cooldown) → activate → commit (pay cost, start cooldown) → do the work, often over time with ability tasks → end. In multiplayer it also handles prediction: the client starts the ability immediately and the server confirms or rolls it back.

Where the ability system component lives

Owner When
on the Character AI enemies, single-player games, anything where state may reset on death
on the PlayerState multiplayer player characters: attributes, cooldowns and effects survive pawn death and respawn

The ASC needs to know its owner (who holds it) and its avatar (the pawn in the world), set with InitAbilityActorInfo on the server and on clients. For the character-owned case below, owner and avatar are the same actor and BeginPlay is a fine place. With a PlayerState-owned ASC, call InitAbilityActorInfo(PlayerState, Pawn) from the pawn's PossessedBy (server) and OnRep_PlayerState (client), because only then do both objects exist.

cpp
// ArenaCharacterBase.h: shared by the player character and the AI enemy
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "AbilitySystemInterface.h"
#include "ArenaCharacterBase.generated.h"

class UAbilitySystemComponent;
class UArenaAttributeSet;
class UGameplayAbility;
class UGameplayEffect;

UCLASS(Abstract)
class ARENA_API AArenaCharacterBase : public ACharacter, public IAbilitySystemInterface
{
    GENERATED_BODY()

public:
    AArenaCharacterBase();
    virtual UAbilitySystemComponent* GetAbilitySystemComponent() const override { return AbilitySystem; }

protected:
    virtual void BeginPlay() override;

    void InitAbilitySystem();

    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Abilities")
    TObjectPtr<UAbilitySystemComponent> AbilitySystem;

    UPROPERTY()
    TObjectPtr<UArenaAttributeSet> Attributes;

    UPROPERTY(EditDefaultsOnly, Category = "Abilities")
    TArray<TSubclassOf<UGameplayAbility>> StartupAbilities;

    UPROPERTY(EditDefaultsOnly, Category = "Abilities")
    TSubclassOf<UGameplayEffect> DefaultAttributesEffect;   // instant GE that sets Health/MaxHealth

    bool bAbilitiesGiven = false;
};
cpp
// ArenaCharacterBase.cpp
#include "ArenaCharacterBase.h"
#include "AbilitySystemComponent.h"
#include "ArenaAttributeSet.h"

AArenaCharacterBase::AArenaCharacterBase()
{
    AbilitySystem = CreateDefaultSubobject<UAbilitySystemComponent>(TEXT("AbilitySystem"));
    AbilitySystem->SetIsReplicated(true);
    AbilitySystem->SetReplicationMode(EGameplayEffectReplicationMode::Mixed);   // Minimal for AI-only actors
    Attributes = CreateDefaultSubobject<UArenaAttributeSet>(TEXT("Attributes")); // subobject sets register with the ASC
}

void AArenaCharacterBase::BeginPlay()
{
    Super::BeginPlay();                             // runs on the server and on every client
    InitAbilitySystem();
}

void AArenaCharacterBase::InitAbilitySystem()
{
    AbilitySystem->InitAbilityActorInfo(this, this);
    if (!HasAuthority() || bAbilitiesGiven) return; // abilities and startup effects are granted by the server

    for (const TSubclassOf<UGameplayAbility>& Ability : StartupAbilities)
    {
        AbilitySystem->GiveAbility(FGameplayAbilitySpec(Ability, /*Level*/ 1, INDEX_NONE, this));
    }
    if (DefaultAttributesEffect)
    {
        FGameplayEffectContextHandle Ctx = AbilitySystem->MakeEffectContext();
        AbilitySystem->ApplyGameplayEffectToSelf(DefaultAttributesEffect.GetDefaultObject(), 1.f, Ctx);
    }
    bAbilitiesGiven = true;
}

An ability in C++

cpp
// GA_Dash.h
#pragma once

#include "CoreMinimal.h"
#include "Abilities/GameplayAbility.h"
#include "GA_Dash.generated.h"

UCLASS()
class ARENA_API UGA_Dash : public UGameplayAbility
{
    GENERATED_BODY()

public:
    UGA_Dash();

    virtual void ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo,
                                 const FGameplayAbilityActivationInfo ActivationInfo,
                                 const FGameplayEventData* TriggerEventData) override;

protected:
    UPROPERTY(EditDefaultsOnly, Category = "Dash")
    float DashStrength = 1800.f;
};

// GA_Dash.cpp
#include "GA_Dash.h"
#include "ArenaTags.h"
#include "GameFramework/Character.h"

UGA_Dash::UGA_Dash()
{
    InstancingPolicy = EGameplayAbilityInstancingPolicy::InstancedPerActor;
    NetExecutionPolicy = EGameplayAbilityNetExecutionPolicy::LocalPredicted;
    ActivationBlockedTags.AddTag(TAG_Status_Stunned);   // can't dash while stunned
    // CostGameplayEffectClass and CooldownGameplayEffectClass are set in the Blueprint child (GA_Dash_BP):
    //   GE_Dash_Cost: instant, Stamina Add -30 (add a Stamina attribute like Health)
    //   GE_Dash_Cooldown: duration 2 s, grants tag Cooldown.Dash
}

void UGA_Dash::ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo,
                               const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData)
{
    if (!CommitAbility(Handle, ActorInfo, ActivationInfo))     // pays the cost and starts the cooldown, or fails
    {
        EndAbility(Handle, ActorInfo, ActivationInfo, /*bReplicateEndAbility*/ true, /*bWasCancelled*/ true);
        return;
    }

    if (ACharacter* Character = Cast<ACharacter>(ActorInfo->AvatarActor.Get()))
    {
        const FVector Dir = Character->GetLastMovementInputVector().GetSafeNormal(0.01f, Character->GetActorForwardVector());
        Character->LaunchCharacter(Dir * DashStrength + FVector(0, 0, 150.f), /*XY override*/ true, /*Z override*/ false);
    }
    EndAbility(Handle, ActorInfo, ActivationInfo, true, false);
}

Activate it from input: AbilitySystem->TryActivateAbilityByClass(UGA_Dash::StaticClass()), or by tag with TryActivateAbilitiesByTag. Lyra and the GAS community samples bind Enhanced Input actions to abilities through input tags, a cleaner pattern once you have many abilities.

For abilities that take time, use ability tasks: UAbilityTask_PlayMontageAndWait, UAbilityTask_WaitGameplayEvent (wait for the notify "Event.Montage.Hit"), UAbilityTask_WaitTargetData, UAbilityTask_WaitDelay. The ability stays active until the task's callback calls EndAbility.

Blueprints are usually the better tool for the ability graph itself: once the C++ base class and attribute set exist, designers build most abilities as Blueprint subclasses of UGameplayAbility with tasks as latent nodes. C++ abilities make sense for core, performance-sensitive or heavily networked ones.

A runnable model of activation

The model implements CanActivateAbility (blocked tags, cooldown tag, cost check), CommitAbility and tag-granting cooldown effects, and tries a dash on several frames.

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

struct ASC {
    double Stamina = 50;
    std::set<std::string> Tags;
    std::map<std::string, double> TagTimers;           // tags granted by duration effects

    void Tick(double dt) {
        for (auto it = TagTimers.begin(); it != TagTimers.end();) {
            it->second -= dt;
            if (it->second <= 1e-9) { Tags.erase(it->first); it = TagTimers.erase(it); }
            else ++it;
        }
        Stamina = std::min(100.0, Stamina + 5 * dt);   // a regen effect: 5 per second
    }
};

struct Ability {
    std::string Name, CooldownTag; double Cost, Cooldown; std::set<std::string> BlockedBy;

    std::string CanActivate(const ASC& a) const {
        for (const auto& t : BlockedBy) if (a.Tags.count(t)) return "blocked by " + t;
        if (a.Tags.count(CooldownTag)) return "on cooldown (" + CooldownTag + ")";
        if (a.Stamina < Cost) return "cannot afford cost";
        return "";
    }
    void TryActivate(ASC& a, double t) const {
        std::cout << "t=" << t << " " << Name << ": ";
        std::string why = CanActivate(a);
        if (!why.empty()) { std::cout << "failed, " << why << "\n"; return; }
        a.Stamina -= Cost;                                   // CommitAbility: cost...
        a.Tags.insert(CooldownTag);                          // ...and cooldown GE granting a tag
        a.TagTimers[CooldownTag] = Cooldown;
        std::cout << "ACTIVATED, stamina now " << a.Stamina << "\n";
    }
};

int main() {
    std::cout << std::fixed << std::setprecision(1);
    ASC asc;
    Ability dash{"GA_Dash", "Cooldown.Dash", 30, 2.0, {"Status.Stunned"}};

    double t = 0;
    const double dt = 0.5;
    std::map<double, std::string> script = {{0.0, "dash"}, {0.5, "dash"}, {2.0, "dash"}, {2.5, "stun"},
                                            {3.0, "dash"}, {4.0, "unstun"}, {4.5, "dash"}, {5.0, "dash"}};
    for (int step = 0; step <= 10; step++, t += dt) {
        if (step > 0) asc.Tick(dt);
        auto it = script.find(t);
        if (it == script.end()) continue;
        if (it->second == "dash") dash.TryActivate(asc, t);
        if (it->second == "stun") { asc.Tags.insert("Status.Stunned"); std::cout << "t=" << t << " stunned\n"; }
        if (it->second == "unstun") { asc.Tags.erase("Status.Stunned"); std::cout << "t=" << t << " stun ends\n"; }
    }
}
t=0.0 GA_Dash: ACTIVATED, stamina now 20.0
t=0.5 GA_Dash: failed, on cooldown (Cooldown.Dash)
t=2.0 GA_Dash: ACTIVATED, stamina now 0.0
t=2.5 stunned
t=3.0 GA_Dash: failed, blocked by Status.Stunned
t=4.0 stun ends
t=4.5 GA_Dash: failed, cannot afford cost
t=5.0 GA_Dash: failed, cannot afford cost

In real GAS the cost and cooldown are gameplay effects (GE_Dash_Cost, GE_Dash_Cooldown), the cooldown is "the target has tag Cooldown.Dash", and the stun is a tag granted by another effect. Everything is the same three questions: tags, cost, cooldown.

Test yourself

Why put the ASC on the PlayerState for multiplayer player characters?

  1. PlayerStates tick faster
  2. Attributes, cooldowns and effects survive the pawn being destroyed and respawned
  3. It's required by GAS
  4. Characters can't own components

What does CommitAbility do?

  1. Ends the ability
  2. Checks and applies the cost and cooldown; fails if they can't be paid
  3. Replicates the ability class
  4. Plays the montage

How does GAS usually represent 'this ability is on cooldown'?

  1. A float timer on the ability
  2. A duration gameplay effect that grants a cooldown tag
  3. A boolean on the character
  4. A Behavior Tree decorator