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

Instantiating Dynamic Objects with NewObject

Learn to safely allocate UObject-derived classes in memory using the NewObject template to ensure proper integration with the engine's reflection system.

In this lesson, you will learn how to properly instantiate dynamic, non-actor UObject instances using the NewObject template to ensure they are tracked by Unreal’s memory management system.

Why Not Use new?

In standard C++, you might be tempted to create objects using the new keyword. However, in Unreal Engine, objects that derive from UObject must be created through the engine’s factory system. If you use new, the engine’s Garbage Collector (GC) won't know the object exists, leading to memory leaks or—worse—the engine prematurely deleting your object because it thinks it’s unused.

NewObject serves as the official bridge between your code and the Reflection System, ensuring your object is correctly registered and eligible for automatic memory management.

The Syntax of NewObject

The template is straightforward to use. You specify the class type as the template argument and provide the "Outer" object (the owner) as the primary parameter. The "Outer" is usually the class where the object is being created (like an Actor or GameInstance).

// Example: Creating a custom Data Object inside an Actor
UMyCustomData* MyDataInstance = NewObject<UMyCustomData>(this);

if (MyDataInstance)
{
    // Now you can safely use your object!
    MyDataInstance->InitializeData();
}

Important Considerations

  1. The Outer Parameter: Passing this as the Outer establishes a hierarchical relationship. When the owner (the Actor) is destroyed or garbage collected, it helps the engine track the lifecycle of your dynamic object.
  2. Memory Safety: By using NewObject, you ensure that the UObject metadata—which you learned about in previous lessons regarding the Reflection System—is properly initialized. If you don't use this factory method, functions like GetName() or any UPROPERTY() fields inside your class will likely cause crashes because the underlying metadata hasn't been built.
  3. UPROPERTY usage: Always remember to store your created object in a UPROPERTY() pointer within your header file. This tells the Garbage Collector, "Keep this object alive as long as I own it," preventing it from being cleaned up while it is still in use.

Key Takeaway: Never use the C++ new keyword for UObject types; always use NewObject<T>() to allow the engine’s Garbage Collector and Reflection System to safely manage the memory and lifecycle of your dynamic instances.