What is the correct way to create and add components at runtime ?

Hi cmartel, thank you for your answer. It led me to look into the AActor source code and I think that aside InitializeComponent the only other missing step is calling OnComponentCreated.

So my code ended looking something like this :



UMyActorComponent* ActorComponent = ConstructObject<UMyActorComponent>(UMyActorComponent::StaticClass(), this);
ActorComponent->OnComponentCreated();
ActorComponent->RegisterComponent();
if (ActorComponent->bWantsInitializeComponent) ActorComponent->InitializeComponent();


And in case the component inherits from USceneComponent then it should be attached too.

Edit: Hey, it’s me from the future! Now OnComponentCreated() and InitializeComponent() are called from RegisterComponent() so don’t call them manually anymore.

3 Likes