Create static meshes in construction script using C++

There are very few information or documentation about how to create and attach static mesh components in construction scripts using C++. I was able to make almost everything work, but, since the mobility of the mesh is set to “static”, every time the editor is restarted, the light build is lost. However, when creating static meshes in construction scripts using Blueprint, it works fine and the light build issue does not happen.

This is the code that I’m using to create the static mesh, given a “Mesh” asset. This code is running inside the OnConstruction function:

UStaticMeshComponent* MeshComponent = NewObject<UStaticMeshComponent>(this);
MeshComponent->SetStaticMesh(Mesh);
MeshComponent->SetMobility(EComponentMobility::Static);
MeshComponent->AttachToComponent(RootComponent, FAttachmentTransformRules(EAttachmentRule::KeepRelative, false));
MeshComponent->RegisterComponent();
MeshComponent->CreationMethod = EComponentCreationMethod::UserConstructionScript;
Meshes.Add(MeshComponent); // Meshes is a UPROPERTY declared in the .h file

Is something missing?

Hmmm…nothing stands out.

Did you make it a UPROPERTY in the h file? Sometimes Unreal does strange things if you don’t use the macros.

Though, I’m not sure why that would affect lighting, of all things.

Yes, I did. A TArray, actually. I will update the original post with this info.

I think it affects the lighting because the lighting is, somehow, marked as “dirty” when a new shape is added to the world. And Unreal thinks the construction script is adding a new shape. However, for some reason, it doesn’t happen when the same code is made using Blueprints. It seems like the Blueprint code is flagging the component, or something like that, to make it not mark the lighting as dirty. I’m looking into UE4 code, but I couldn’t find any clue so far.