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!

Hello, twolink

Please note that your Static Mesh Component is a local variable within a function. To fix the issue, please declare the appropriate property in the header file:

UPROPERTY(EditAnywhere)
UStaticMeshComponent* meshComponent;

Thus, in OnConstruct() you’ll just need to initialize it:

meshComponent = ConstructObject<UStaticMeshComponent>(UStaticMeshComponent::StaticClass(), this);

Hope this helped!

Have a great day!

Hey.

That worked. I thought putting the component into the Actor hierarchy using meshComponent->AttachTo(GetRootComponent())
would solve all lifetime issues. I guess when switching to play mode Unreal makes a copy of the original Actor instance und only takes UPROPERTY-declared components into account? Probably I should read a little more code to fully understand the UPROPERTY-Macro-Magic. :wink:

Thanks a lot.