When is valid time to create Subobjects/Components?

I’m trying to create instances of components and attach them to my object, but I get the following error:

UE_CLOG(!CurrentInitializer, LogObj, Fatal, TEXT("No object initializer found during construction."));

I tried calling it this way, in various places:

auto WidgetComponent = CreateDefaultSubobject<UWidgetComponent>(TEXT("WidgetComponent"));

It throws the error if I call it from BeginPlay or PostInitializeComponents.

Is it really impossible to call it outside the constructor?

1 Like

You can create SubObjects/Components anywhere. You can only call CreateDefaultSubobject from the constructor.

To create a component at runtime you must use ConstructObject().

UWhateverComponent* NewComponent = ConstructObject<UWhateverComponent>(UWhateverComponent::StaticClass(), this, TEXT("ComponentName"));

NewComponent->RegisterComponent();
NewComponent->OnComponentCreated(); // Might need this line, might not.
NewComponent->AttachTo(GetRootComponent(), SocketName /* NAME_None */);

There may be a compiler error with missing args in AttachTo, but this is how you create and attach components at runtime.

As of 4.8, ConstructObject is deprecated and you should use NewObject instead.

2 Likes

Another incomplete/misleading tutorial here…
https://docs.unrealengine.com/en-us/Programming/Tutorials/Components/1

welcome to Unreal, here you rarely find complete documentation with working code