Adding and using Gameplay Tags in C++
Updated for UE 5.8: I recommend the
UE_DEFINE_GAMEPLAY_TAGmacros over this approach, see Native Gameplay Tags.FGameplayTagNativeAdderstill exists in 5.8 and now registers throughCallOrRegister_OnAddNativeTagsDelegate(the oldOnLastChanceToAddNativeTagsdelegate is deprecated), and I have fixed the sample code below.
One of the many questions I see and get asked is how to add and use Gameplay Tags inside C++. There are many ways to do it, but Unreal Engine has a nice base struct we can use for this purpose, and we can derive our own struct from it to register the tags and give us clean C++ accessors.
FGameplayTagNativeAdder is the struct we want to derive from, and it has one pure virtual method, AddTags. Its constructor registers with the GameplayTagsManager, and AddTags runs when native tags are being added (or straight away if that has already happened). That’s just what we need.
Let us construct the struct. We do basically everything in the header, except one line in the cpp for the static definition.
// Copyright InterKaos Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GameplayTagsManager.h"
struct KAOSGAME_API FKaosGlobalTags : public FGameplayTagNativeAdder
{
// Set by caller tag which specifies duration of a Gameplay Effect
FGameplayTag SetByCaller_Duration;
// Tag used for Fire Damage
FGameplayTag Damage_Fire;
// Static accessor for the tags. Access tags using:
// FKaosGlobalTags::Get().Damage_Fire for example.
FORCEINLINE static const FKaosGlobalTags& Get() { return KaosTags; }
protected:
// Called to register and assign the native tags
virtual void AddTags() override
{
UGameplayTagsManager& Manager = UGameplayTagsManager::Get();
SetByCaller_Duration = Manager.AddNativeGameplayTag(TEXT("SetByCaller.Duration"));
Damage_Fire = Manager.AddNativeGameplayTag(TEXT("Damage.Fire"));
}
private:
// Private static object for the global tags. Use the Get() function to access externally.
static FKaosGlobalTags KaosTags;
};
Now we need one line in the cpp file to define the static:
FKaosGlobalTags FKaosGlobalTags::KaosTags;
Now we can access our native tags from anywhere in the project. For example:
UAbilitySystemBlueprintLibrary::SendGameplayEventToActor(Actor, FKaosGlobalTags::Get().Damage_Fire, EventParams);
If you have a lot of tags used in C++, you can make multiple structs for the different types.
Notes:
AddNativeGameplayTagtakes an optional developer comment as its second parameter (default"(Native)"), so you can document your tags here too.AddNativeGameplayTag(FName, ...)is still valid in 5.8, but for new code the macro-based approach is less boilerplate and is what I use now.
Hope this helps you easily add and use Gameplay Tags in C++.