How can I add components in the OnConstruction function?

How can I add components in the OnConstruction function?

What I have tried so far

void AFoo::OnConstruction(const FTransform& Transform)
{
    USplineMeshComponent *s = ConstructObject<USplineMeshComponent>(USplineMeshComponent::StaticClass());
    FVector v(10,10,10);
    s->SetStartAndEnd(v, v, v,v);
}

The problem is that this will result in an editor crash. The following code throws the error where PersistentLevel points to corrupt memory.

bool UWorld::AreActorsInitialized() const
{
	return PersistentLevel && PersistentLevel->Actors.Num() && bActorsInitialized;
}

Do I need to use AActor::AddComponent | Unreal Engine Documentation ?

Are you sure you want OnConstruction and not an ObjectInitializer or PostBeginPlay?

USplineMeshComponent* SplineMesh = ConstructObject(USplineMeshComponent::StaticClass(), this);

	SplineMesh->CreationMethod = EComponentCreationMethod::UserConstructionScript;
    RegisterAllComponents();

You are probably missing the CreationMethod line. If you are on an earlier version of the engine, it was a boolean called bCreatedByConstructionScript.

What is happening in your case is probably that the component is created a lot of time and never cleaned. Also, do not forget to Register each components :slight_smile: You can also use RegisterAllComponents(); like in the example above to do it for all of them.

Hope this helps!

Mick

Thanks a lot I would have never figured this one out by myself. Is this documented somewhere?

I’ve never seen it documented, found it out by searching around :slight_smile: You can accept the answer again…looks like commenting on it means it’s not valid anymore :stuck_out_tongue: