Course contentsShow
← Unreal Engine Game Development
Lesson 170 of 8803. C++ and UObject ArchitectureFree lesson

Forcing Object Persistence with AddToRoot

Use the AddToRoot function to explicitly protect specific objects from being garbage collected, regardless of their current reference count in the game.

In this lesson, you will learn how to manually protect specific UObject instances from being destroyed by the Garbage Collector using the AddToRoot function.

Understanding the Lifecycle Problem

So far, you’ve learned that Unreal Engine’s Garbage Collector (GC) tracks UObjects and deletes them if they are no longer referenced by a UPROPERTY. While this is great for memory management, sometimes you need an object to exist for the entire duration of the application, regardless of whether any other class is currently "holding" onto it.

Normally, if you create an object with NewObject and don't store it in a UPROPERTY within an existing actor or class, the GC will identify it as "unreachable" and delete it during the next sweep. AddToRoot is our way of telling the engine, "Ignore the reference count—this object must stay alive."

Using AddToRoot

When you call AddToRoot() on an instance, you are effectively placing it in a protected internal list that the Garbage Collector will never clear. This is particularly useful for global managers or data objects that need to persist independently of any specific actor's lifecycle.

Here is how you implement it:

// Assuming 'MyCustomObject' is a UObject
UMyCustomObject* PersistentObj = NewObject<UMyCustomObject>();

// Force the engine to keep this alive indefinitely
PersistentObj->AddToRoot();

Important Considerations

Because you have manually forced the object to stay in memory, the engine will no longer clean it up automatically, even when you change levels or close the game. You must pair this with RemoveFromRoot() when you are finished with the object, or you will create a permanent memory leak.

// When you are truly done with the object:
PersistentObj->RemoveFromRoot();

Use this power sparingly. It is a "brute force" method for managing memory and should only be used when standard UPROPERTY ownership chains (like storing references in your GameInstance or Subsystems) aren't feasible for your specific architectural needs.

Key Takeaway: AddToRoot manually adds an object to the Garbage Collector's protected list to prevent it from being deleted, but it requires a matching RemoveFromRoot call to prevent memory leaks.