It is actually possible to do this. The following code is modified from Add component to actor in C++ (the final word!) - #15 by Curs0
At the top:
#if WITH_EDITOR
#include "UnrealEd.h"
#endif
In your constructor:
if(GetOwner() == nullptr)
{
return;
}
UActorComponent* MyBox = GetOwner()->GetComponentByClass(UBoxComponent::StaticClass());
if(MyBox == nullptr)
{
UBoxComponent* BoxComponent = NewObject<UBoxComponent>(GetOwner(), TEXT("NewBoxComponent"));
if (IsValid(BoxComponent))
{
GetOwner()->AddInstanceComponent(BoxComponent);
BoxComponent->AttachToComponent(GetOwner()->GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
// deselect/select this actor to update Editor details
#if WITH_EDITOR
USelection* Selection = GEditor->GetSelectedActors();
Selection->Deselect(GetOwner());
GEditor->SelectActor(GetOwner(), true, true);
#endif
}
}
This will add the box component if you add this custom component to an actor in a level, but not if you add the custom component in the Blueprint Editor. However, if you’re doing this often enough in the Blueprint Editor that it’s too frustrating to add them manually, then you should probably take a look at your program design or at the very least do child classes. I think there is also some macro functionality that will allow you to just add a bunch of stuff with a click of a button, but I haven’t played around with it to know how.