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.

1 Like

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

5 Likes

Another incomplete/misleading tutorial here…

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

1 Like

I’m posting few lines of code just to keep the topic up to date since ConstructObject and AttachTo are deprecated:

void AActorWithInstancedComponent::OnConstruction(const FTransform& Transform)
{
	Super::OnConstruction(Transform);
	 
	class UTestComponent* NewComponent = NewObject<UTestComponent>(this,UTestComponent::StaticClass(), TEXT("NewComponent"));

	NewComponent ->RegisterComponent();

	NewComponent ->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
}

AttachToComponent() only works for USceneComponent and its children and not for UActorComponent

7 Likes