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

Optimizing Memory with Structs and USTRUCT

Define complex data structures using USTRUCT to keep memory layout efficient while maintaining compatibility with the reflection and serialization systems.

In this lesson, you will learn how to use USTRUCT to organize your game data efficiently while ensuring Unreal Engine can see and manage it.

Why Use Structs?

When you have a group of related variables—like a player’s health, ammo, and armor—it is messy to keep them floating as individual variables in a class. A struct (short for structure) allows you to group these related pieces of data into a single, compact block of memory.

In Unreal Engine, a plain C++ struct is "invisible" to the editor. To make it work with the engine’s powerful reflection and serialization systems, we use the USTRUCT macro. This tells Unreal to track the data, allow it to be edited in the Details panel, and handle it correctly during save/load operations.

Defining a USTRUCT

When you define a USTRUCT, you create a custom data type that acts like a specialized container. Here is how a basic structure for an "InventoryItem" looks:

USTRUCT(BlueprintType)
struct FInventoryItem
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere)
    int32 ItemID;

    UPROPERTY(EditAnywhere)
    float Weight;

    // Default constructor is required for USTRUCTs
    FInventoryItem() : ItemID(0), Weight(0.0f) {}
};

Memory Efficiency and Organization

By grouping variables into a USTRUCT, you improve data locality. Because the engine stores these variables contiguously (side-by-side) in memory, the CPU can access them much faster than it could if they were scattered throughout an object.

Furthermore, because you marked the members with UPROPERTY, Unreal’s Garbage Collector knows exactly what is inside your struct. If you store an AActor* or another UObject* inside your USTRUCT, the reflection system ensures that those objects are protected from being cleaned up unexpectedly while your struct is in use.

This approach keeps your UCLASS files cleaner, as you can move complex data groupings into their own structs, making your architecture more modular and much easier to debug in the editor.

Key Takeaway: Use USTRUCT to bundle related data, which improves memory layout, simplifies data management in the editor, and ensures compatibility with Unreal’s serialization and garbage collection systems.