Adding Components to Actor in OnConstruction()

Hello everyone.

I am trying to add static mesh components to my own Actor-derived class during construction:

void AMyActor::OnConstruction(const FTransform& Transform)
{
	UStaticMeshComponent* meshComponent = ConstructObject<UStaticMeshComponent>(UStaticMeshComponent::StaticClass(), this);
	meshComponent->CreationMethod = EComponentCreationMethod::UserConstructionScript;
	meshComponent->AttachTo(GetRootComponent());
	meshComponent->RegisterComponent();
}

This really works fine as long as I am in editor mode. I can see the component in hierarchy view. But when switching to play mode the constructed static mesh component won’t show up. The only persistent component is the root scene node which was added in the constructor of my class:

SetRootComponent(ObjectInitializer.CreateDefaultSubobject<USceneComponent>(this, "MyRootNode"));

What am I missing? I am using Version 4.7.6.

Thanks for your help!

I’m not sure exactly why this would go wrong, but I just use the following and it works perfectly fine for standalone as well:

// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;

// Dummy Scene Comp
DummyComp = CreateDefaultSubobject<USceneComponent>(TEXT("DummyComp"));
RootComponent = DummyComp;

// Some Mesh
ArmMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ArmMesh"));
ArmMesh->AttachParent = RootComponent;

I don’t think you need to call RegisterComponent when creating it in the Constructor.

Hey staticvoidlol.

Thanks for your response. What I’m trying to do is to control the amount of created objects through a property. That way I would be able to tweak things in editor mode. This is why I am creating my components in OnConstruction(). But CreateDefaultSubobject can only be used inside of UObjects constructors. Maybe I have to dig a little deeper into the source.

Best regards.

Ah my mistake - I didn’t see you’re doing this in OnConstruction(). I know there’s a lot of black magic going on in the editor regarding constructors, but have no idea why this would be happening. Good luck.

Hey staticvoidlol,

Did you manage to figure out how to create components inside OnConstruction?

Solution in duplicate post: