Course contentsShow
← Unreal Engine Game Development
Lesson 43 of 8801. Foundations and Editor WorkflowFree lesson

Creating Custom Type Traits for Reflection

Extend the reflection system by creating custom traits to categorize or filter your game classes during runtime procedural generation tasks.

In this lesson, you will learn how to create custom "traits" to categorize your game classes, allowing you to filter them efficiently during runtime procedural generation tasks.

The Concept of Traits

In Unreal Engine, the reflection system knows a lot about your classes—like their name, size, or memory address. However, it doesn't inherently know if a class belongs to a specific "category," such as "Lootable," "Destructible," or "Enemy." A custom trait is simply a piece of metadata we attach to a class that acts as a label. When your game performs a procedural task—like randomly spawning items in a dungeon—you can use these traits to ask the engine, "Give me all classes that have the 'Lootable' trait."

Implementing Traits with Metadata

The easiest way to implement this is by leveraging the meta specifier within your UCLASS macro. By adding a custom key-value pair, you create a searchable tag that the reflection system can read at runtime.

UCLASS(meta = (Category = "Spawnable", Rarity = "Legendary"))
class ALootChest : public AActor 
{
    GENERATED_BODY()
};

Querying Traits at Runtime

Once you have tagged your classes, you can query this information using UClass::GetMetaData. This allows you to perform logic based on your custom traits without needing to hard-code lists of classes or rely on complex inheritance hierarchies.

FString Rarity = MyClass->GetMetaData(TEXT("Rarity"));
if (Rarity == TEXT("Legendary"))
{
    // Perform procedural logic specific to legendary items
}

By using this approach, you decouple your procedural systems from your class hierarchy. Instead of forcing all loot into a single ALoot base class, you can have diverse actors across your project that all share the "Lootable" trait via metadata. This makes your systems significantly more modular and easier to expand, as adding a new object to your generator is as simple as adding a line of metadata to its UCLASS declaration.

Key Takeaway: Custom type traits allow you to label classes with metadata, enabling your procedural systems to filter and categorize actors dynamically without rigid inheritance.