Add component to actor in C++ (the final word!)

Thanks all for your suggestions.

Just to say the final word, the following code is confirmed to work on UE5.3

#if WITH_EDITOR
#include "UnrealEd.h"
#endif

...

#if WITH_EDITOR
...
UBoxComponent* BoxComponent = NewObject<UBoxComponent>(this, TEXT("NewBoxComponent"));
if (IsValid(BoxComponent))
{
   AddInstanceComponent(BoxComponent);
   BoxComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
   // deselect/select this actor to update Editor details
   USelection* Selection = GEditor->GetSelectedActors();
   Selection->Deselect(this);
   GEditor->SelectActor(this, true, true);
}
...
#endif
2 Likes