AddActor in the editor via C++ module

Hi I’m trying to place some actor in the map via C++. The code runs in a secondary module associated with a menu item in the editor.

void FLevelStreamModule::OnMenuEntry()
{
	AStaticMeshActor* CubeActor = Cast<AStaticMeshActor>(GEditor->AddActor(
    	GetWorld()->GetCurrentLevel(), AStaticMeshActor::StaticClass(), 
		FTransform(FVector(0))));
	CubeActor->GetStaticMeshComponent()->StaticMesh = LoadObject<UStaticMesh>(nullptr, 
		TEXT("StaticMesh'/Engine/EditorMeshes/EditorCube.EditorCube'"));

	GEditor->EditorUpdateComponents();
	CubeActor->GetStaticMeshComponent()->RegisterComponentWithWorld(GetWorld());
	GetWorld()->UpdateWorldComponents(true, false);
	CubeActor->RerunConstructionScripts();
	GLevelEditorModeTools().MapChangeNotify();
}

The actor is is visible in the scene outliner but the mesh is doesn’t appear in the viewport. But when I change any property of the actor from the editor it magically start drawing. How can I notify the editor to start drawing my cube?

I’ve run into the same issue and figured it out.

You need to call “MarkComponentsRenderStateDirty();” on StaticMeshActor.

Also, you don’t need to call EditorUpdateComponents and the rest of the functions.

You only need:

“CubeActor->GetStaticMeshComponent()->StaticMesh = LoadObject” Followed by call to “MarkComponentsRenderStateDirty()” and that’s it.

It looks like setting the StaticMesh component of an actor directly is soon going to be deprecated. I’m running 4.16 and getting a warning. I ended up using this.

CubeActor->GetStaticMeshComponent()->SetStaticMesh(LoadObject(nullptr, TEXT(“StaticMesh’/Engine/EditorMeshes/EditorCube.EditorCube’”)));

If you use this you do not have to use “MarkComponentsRenderStateDirty()”

Thanks for the post. I was lost without finding this.