{ }Blueprint → C++

Unreal Engine 5 · Blueprint → C++

Create a Component in the Constructor in UE5 C++UE Docs

Creating a component in Blueprint's Components panel maps to CreateDefaultSubobject<T>() in the Actor constructor, the only place default subobjects can be created in C++.

Blueprint node & C++ equivalent

C++
// .h
UPROPERTY(VisibleAnywhere)
UStaticMeshComponent* Mesh;

// .cpp constructor
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
RootComponent = Mesh;                 // or: Mesh->SetupAttachment(RootComponent);

The C++ equivalent

Declare the component pointer in the header with UPROPERTY(VisibleAnywhere) so it shows in the Details panel, then instantiate it inside the constructor with Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh")). The string passed to TEXT(...) is the internal subobject name and must be unique within the Actor.

Set it as the root with RootComponent = Mesh, or attach it to an existing root with Mesh->SetupAttachment(RootComponent).

Why it must be in the constructor

CreateDefaultSubobject can only be called during construction because it registers the component as a default subobject of the class default object. Calling it later will assert. To add components after construction, use NewObject and RegisterComponent at runtime instead.

Using VisibleAnywhere rather than EditAnywhere is intentional: you can inspect the component but not reassign the pointer, which protects the subobject.

Frequently asked questions

How do I add a component to an Actor in UE5 C++?+

In the constructor call CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh")) and then either set it as RootComponent or call SetupAttachment.

Can I call CreateDefaultSubobject outside the constructor?+

No. It must run during construction. For runtime components use NewObject followed by RegisterComponent and AttachToComponent.

Related Components nodes

View all Components nodes →