Forays into Unreal Engine’s Gameplay Ability System

I will preface this post by saying that I am not a professional game developer – I am a professional software developer who happens to make games in his spare time. Most recently, I’ve been working in Unreal Engine 5 on an action RPG project, which was originally kicked off over a year ago with long periods of inactivity as life happened. I have been coming back to working on this project more in recent months as a sort of therapeutic practice – engaging with the craft of software engineering that I fell in love with in the first place a decade ago.

I will note, as a software engineer in tech, I use LLMs in my professional life as the job now dictates. At the start of this project, I would still occasionally use LLMs as a search engine for unreal documentation + best practices and as a way to check over some of my code and architecture ideas. I have since pivoted back to a manual workflow, making a conscious choice to eschew the use of LLMs and focus on craft, learning, and intentional decision making over convenience in my personal life.

The project is presently under the working title “Dark Forest” (more out of reference to Symbaroum‘s forest of Davokar than Cixin Liu’s Three Body Problem sequel). It is intended to be a class-based horde-mode style cooperative game about defending your base from hostile forces in contained 10-15 minute matches. This post is detailing some learnings I’ve found with using Unreal’s Gameplay Ability System (GAS) for my purposes.

Preface: reference materials

If you’ve been searching for info on GAS, you’ve probably stumbled across Tranek’s GASDocumentation repo, and for good reason. This is one of the more comprehensive pieces of documentation on GAS with some generally good default recommendations/advice on what features to use, and what not to use. This is the first place I look when trying to understand some of the obscure, fiddly bits of GAS.

This post from Laura’s (Mostly) Unreal Blog was also helpful as a quickstart for some of the initial setup work you need to get to the “fun” parts of GAS. (Namely, that means setting up attribute sets, initial gameplay effects, etc.). My post assumes such setup work is done and familiar to the reader.

Finally, X157’s Dev Notes pages were useful for understanding how to extend gameplay abilities to send data via Server-to-Client RPCs.

With these in mind, let’s proceed with the rest of the post.

Embrace gameplay tags…

Gameplay tags are really neat. They act as a hierarchical labeling system flexible enough for all sorts of purposes – describing an ability, enforcing ability constraints, denoting what status effects are applied to a player, catalogs of events to fire, etc.

The most immediately visible functionality can be seen right when you first create a Gameplay Ability – you can assign tags to an ability, tell it what tags to apply to the owning actor, what prerequisite tags are required for activation, and what tags are mutually exclusive and would block the ability from activating.

Those last few pieces are quite powerful! Say you only want an ability to work if the player is already aiming, and conversely you want an ability to never fire if the player is aiming. The ability to designate that is already built into your abilities without any additional mapping on your part. That said, you may wish to build a mapping regardless so you don’t accidentally miss a tag requirement/exclusion on a new ability variant or otherwise have to manage these per-ability. For example, Lyra builds out a top-level mapping that allows setting specific tags/hierarchies to automatically block other relevant tags. Having these relationships respected by GAS out of the box is quite neat, and is certainly loads better than having various exclusive states littered as bools throughout your code that you need to keep checking.

Nice and tidy, in one place

…even in unexpected places

I want to talk about another fun use case though: events via AnimNotifies!

See, one thing you probably find yourself doing a lot in your Gameplay Abilities is playing AnimMontages. And, if you’re like me, you might have been using custom notifies to drive game behavior like activating weapon hitboxes. This means a lot of custom event handlers got defined in your Animation Blueprints and wired through to your pawn/character/actor component classes. This creates a bit of a tangled mess that feels unpleasant, especially if you have multiple Animation BPs for different character types but need to handle common notifies.

Feels wrong for the AnimBP to own this!

Using gameplay tags as event messages provides us a nice mechanism for getting around this, and allows us to have our Gameplay Abilities to respond to events from the anim notifies. We can define custom AnimNotify subclasses that pass gameplay tags to our actor – or we can define a generic AnimNotify that takes arbitrary input tags, though those do not stand out at a glance when inspecting your animation timeline.

Simple custom notify for combo windows, sending a gameplay tag to the owner.
Custom notifies per use case – defining windows for combos, hit scan, and root motion rotation.

Receiving events then becomes the responsibility of the ability:

To me, this pattern feels “cleaner”. The animation is still firing events, but the actual behavior resulting from these events become scoped to the ability, rather than the animation blueprint mutating player state directly.

One caveat that bit me and comes with the territory of anim notifies generally: notifies are not super precise and aren’t guaranteed to fire. I found that a notify placed near the end of an animation/montage section would be liable to drop and not fire due to the animation blending out first. The timing of what “works” changes depending on the animation speed and the blend out time (and likely a host of other factors). In my case, the most reasonable solution was to shrink blend out times on my combat-related anim montages.

Of course, since we make these the ability’s responsibility, this means we have to manage it in each relevant implementation. Which brings me to my next point:

Configurable, reusable abilities are your friend

Let’s start with simple melee attack animations. As mentioned above, we can use anim notifies to handle hitboxes. Assuming that the logic for these are shared, for most attacks, the actual differences between attacks really comes down to a handful of configurable factors:

  • Which animation to use
  • What status to use (damage, stamina use, etc)
  • Special on-hit effects (e.g. elemental damage, DOT, etc.)

What this lead to was having one basic MeleeBase ability, with each distinct ability (jump attack, spin attacks, dash strike, etc.) being a data-only subclass.

Blueprint diff between abilities – note that only 4 values differ

Combos are then a simple extension on top of this that listens for additional inputs and combo window events, and fires off the next attack animation in the combo if things line up.

Where things really got interesting was trying to set up bow & arrow abilities. This, by far, took the most time out of anything in this project, and I plan to write a separate post that is a deep dive into it. A TL;DR is that every extension of a basic bow firing ability felt simple enough to fold into a parent class behind a flag/counter, such as: “can this ability charge”, “how many successive shots should this fire”, “do we fire horizontally fanned shots too”.

This mass of nodes doesn’t even do justice to the C++ going on in the ability base

As this screenshot shows, this means our abilities can get quite complicated. And yet, this up-front work of building a heavily configurable ability leads to a situation where we can now quickly spin up new ability variants with only a few quick variable edits. Triple shot? Fanned shot? Triple fanned shot? Each just a few edits away from each other. This makes iterating on the gameplay piece of gameplay abilities quite quick and opens the door for a lot of future ability variants.

A logical next step is to ask: why have child classes at all? Why not simply have configuration data assets/structs holding the specifics for each attack? And indeed, we can store our configuration in a data asset that gets passed into a base ability spec at grant-time by setting SourceObject, a generic UObject pointer. SourceObject is a bit of a hack in our use case, though. It’s meant to link back to the, well, source of the ability (for instance, if abilities were tied to specific weapons, the weapon could be the SourceObject that grants the player the ability). We can use it to ferry arbitrary data around if we wanted to, but it obscures the original purpose.

For now, I find data-only subclasses work for me. While it multiplies out the number of ability classes, it gives me clarity at a glance of how many abilities I have and gives me a starting point for building overrides or divergent behavior if I find the base ability insufficient. I can then make the call later on whether to fold the divergent behavior into the base class.

With that aside done, I want to introduce my next learning:

Concurrently running abilities can also be your friend

It was not obvious to me from the jump, but having multiple companion abilities running in parallel can actually be a pretty great thing!

A simple example: I want to be able to lock on to enemies, like in Zelda, Dark Souls, etc.

The actual lifecycle of locking on – initiation and cessation – ended up being a nice fit for a gameplay ability that runs independently of other abilities. Meaning, we can have most abilities just work as normal running concurrently. We can also leverage gameplay tag ability blocking behavior to define our mutually exclusive states easily, such as mandating that you can’t free aim and lock on at the same time. All just through tags!

Speaking of aiming, we can peek ahead again to the bow/arrow deep dive. I wanted two paths for bow and arrow abilities: one quickly without aiming, and one that is aimed pretty precisely. Rather than having aiming behavior managed by the actor or an actor component, it seemed reasonable to have aiming itself be an ability that can run alongside, and in fact manage, other abilities.

The aim ability itself can apply an aiming state tag – I called mine State.Ranged.PreciseAiming. Abilities that support aiming can pick up on this tag if they need to exhibit special behaviors such as charging / waiting for additional input (we can also pick this up in our AnimInstance to pass along to our Anim BP for cosmetic behaviors). They can additionally register with the aim ability so that their lifecycles become linked. Some code snippets to demonstrate the interweaving:


# AimAbility.h
/**
 * This ability serves as the entrypoint for aimed range abilities.
 * It not only manages the aiming combat state, but also serves as a sort
 * of registry of aiming-capable abilities which are currently running.
 */
UCLASS()
class UAimAbility : public UDFGameplayAbility
{
...
  	UFUNCTION()
	void ActivateDefaultAbility();
	// Will end the ability if able - that is, if the input button
	// has been released and the child ability has completed.
	void EndAbilityIfFinished();

  	bool RegisterChildAbility(UAimedAbilityBase* ChildAbility);
  	
	UFUNCTION()
	virtual void OnChildAbilityEnded(const UDFGameplayAbility* ChildAbility, const bool bWasCancelled);
  
  	// Default ability to activate when aiming starts
	UPROPERTY(EditDefaultsOnly, Category = "Ability")
	TSubclassOf<UDFGameplayAbility> DefaultAbility;
  	
	UPROPERTY()
	UAimedAbilityBase* ActiveAimedAbility;

  	UPROPERTY()
	TSet<UAimedAbilityBase*> ActiveAimedAbilities;
}

# AimedAbilityBase.h - dervied from a custom GA class that can send transform data from client to server
UCLASS()
class UAimedAbilityBase : public UDFGameplayAbility_LocToServer {
...
  // If there is an active Aim ability running for the owner, register with it.
  void TryRegisterToActiveAimAbility();
}


# AimedAbilityBase.cpp
void UAimedAbilityBase::TryRegisterToActiveAimAbility()
{
	const UAbilitySystemComponent* ASC = GetAbilitySystemComponentFromActorInfo();
	if (!ASC)
	{
		return;
	}
    
	// In my case, we can rely on the aimed ability being tied to the `ClassAction` input for archers
    // Had difficulty attempting to find UAimAbility directly by class, since the actual, executing class is a BP impl
	const FGameplayAbilitySpec* AimSpec = ASC->FindAbilitySpecFromInputID(EAbilityInputID::EAII_ClassAction);
	if (AimSpec == nullptr || !AimSpec->IsActive())
	{
		return;
	}
    
	UAimAbility* AimAbility = Cast<UAimAbility>(AimSpec->GetPrimaryInstance());
	if (!AimAbility)
	{
		return;
	}
    
	AimAbility->RegisterChildAbility(this);
    // So we can notify the aim ability that we have ended
	OnAbilityEnded.AddUniqueDynamic(AimAbility, &UAimAbility::OnChildAbilityEnded);
}

# AimAbility.cpp

bool UAimAbility::RegisterChildAbility(UAimedAbilityBase* ChildAbility)
{
	if (ChildAbility && CanRegisterNewAbility())
	{
		if (ActiveAimedAbility && ActiveAimedAbility->IsActive())
		{
			if (ActiveAimedAbility->CanCleanlyCancel())
			{
				ActiveAimedAbility->CancelAimedAbility();
			}
			else
			{
				UE_LOG(LogTemp, Warning, TEXT("Unable to cancel ability %s"), *ActiveAimedAbility->GetName());
				return false;
			}
		}
		ActiveAimedAbility = ChildAbility;
		return true;
	}
	return false;
}

void UAimAbility::OnChildAbilityEnded(const UDFGameplayAbility* ChildAbility, const bool bWasCancelled)
{
	UE_LOG(LogTemp, Warning, TEXT("OnChildAbilityEnded -> %s"), *ChildAbility->GetName())
	const UAimedAbilityBase* AsAimed = Cast<UAimedAbilityBase>(ChildAbility);
	if (AsAimed && AsAimed == ActiveAimedAbility)
	{
		ActiveAimedAbility = nullptr;
		if (bAimInputHeld)
		{
			// Fire off next frame, once the existing ability is finished
			UE_LOG(LogTemp, Warning, TEXT("Queuing Default Ability"))
			GetWorld()->GetTimerManager().SetTimer(DefaultAbilityTimerHandle, this, &ThisClass::ActivateDefaultAbility, 0.01f, false, 0.0f);
		}
		else
		{
			EndAbilityIfFinished();
		}
	}
}

void UAimAbility::ActivateDefaultAbility()
{
	UAbilitySystemComponent* ASC = GetAbilitySystemComponentFromActorInfo();
	if (!ASC || !Character->HasAuthority()) return;
	// We don't really expect to cancel a non-default ability for a default ability
	if (ActiveAimedAbility && ActiveAimedAbility->GetClass() != DefaultAbility) return;
    
	bool bActivatedDefaultAbility = ASC->TryActivateAbilityByClass(DefaultAbility, true);
	if (!bActivatedDefaultAbility)
	{
		UE_LOG(LogTemp, Warning, TEXT("AimAbility failed to activate child ability"))
		EndAbility(CurrentSpecHandle, CurrentActorInfo, CurrentActivationInfo, true, false);
	}
	GetWorld()->GetTimerManager().ClearTimer(DefaultAbilityTimerHandle);
}

void UAimAbility::EndAbilityIfFinished()
{
	if (ActiveAimedAbility == nullptr && !bAimInputHeld)
	{
		EndAbility(CurrentSpecHandle, CurrentActorInfo, CurrentActivationInfo, true, false);
	}
}

Using ability to drive state, which can be read by both abilities and other systems (like animation) while allowing abilities to “talk” to each other led to some really nice and clean data-driven behaviors. I’m sure it is possible to go overboard here and end up with a pile of spaghetti, so it is worth picking the right kinds of abilities to be either independent or intertwined.

What’s next

I’ve rambled for quite a bit here, so I think I will leave it here as a high level “what I found worked for me with GAS”. I intend to follow up soon with a deep dive into the configurable bow/arrow ability system and walk through some of the hiccups I encountered there. Thanks for reading!

Leave a Reply