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

Analyzing the Unreal Garbage Collection Cycle

Understand how the engine’s mark-and-sweep algorithm identifies unreachable objects and cleans up memory to maintain performance during gameplay sessions.

In this lesson, you will learn how Unreal Engine automatically manages your game's memory using the "Mark-and-Sweep" algorithm to ensure smooth performance.

The Problem: Memory Clutter

As you spawn Actors and create UObjects, your computer’s RAM fills up. If you stop using an object (like a projectile that disappeared or an enemy that was destroyed), simply ignoring it would lead to a "memory leak," eventually crashing your game. Unreal handles this by periodically scanning for "dead" objects that are no longer needed.

How the Algorithm Works

Unreal’s Garbage Collector (GC) runs on a timer and uses a two-phase process called Mark-and-Sweep:

  1. Mark Phase: The engine starts at a list of "Root Objects" (things that are guaranteed to stay alive, like your GameInstance or the World). It follows every reference from these roots, tagging every UObject it can find as "reachable." If an object is not reachable via a chain of references, it is marked as "garbage."
  2. Sweep Phase: The engine goes through the memory, looks for everything that wasn't marked, and deletes it. This clears out the memory, making it available for new objects.

The Role of UPROPERTY()

You might wonder: How does the engine know if I’m still using an object? This is where the UPROPERTY() macro you learned earlier becomes vital.

When you declare a pointer to a UObject as a UPROPERTY(), you are telling the engine's reflection system: "Hey, I am using this object."

UCLASS()
class AMyActor : public AActor
{
    GENERATED_BODY()

    // The GC sees this pointer and knows to keep the object alive
    UPROPERTY()
    UTexture2D* MyDynamicTexture; 
};

If you store a pointer to a UObject without UPROPERTY(), the Garbage Collector cannot "see" it. The collector might think the object is unused and delete it out from under you, leading to a crash when you try to access that memory later.

By keeping your references tagged with UPROPERTY(), you allow the engine to safely track your objects and automatically clean up those that are truly unreachable.

Key Takeaway: The Garbage Collector uses the Mark-and-Sweep algorithm to delete unreachable objects, but it only tracks references correctly if they are marked with the UPROPERTY() macro.