Quick question on adding a component mesh outside of a constructor

Hi, I’ve searched the net and found a few examples of creating a component (i.e. the mesh below) and attaching it to an existing actor but I cannot for the life of me get it displaying on the screen.

I’m using the code from the ‘Generate Procedural Mesh’ tutorial to create the mesh. It works if I create the mesh from the actor’s constructor but I want to create it outside of that (i.e. back in my custom GameMode class), any ideas what I am doing wrong would be helpful, thanks.

// Inside my GameMode - ‘SpawnTerrainActor()’ function:



        FActorSpawnParameters sp;
	sp.Name = "Terrain";
	sp.bNoCollisionFail = true;

	UWorld *world = GetWorld();
	_actor = (ATerrainActor*)world->SpawnActor(
		ATerrainActor::StaticClass(),
		&FVector::ZeroVector, 
		&FRotator::ZeroRotator, 
		sp);
	_actor->PrimaryActorTick.bCanEverTick = true;

	FName NewName = *(FString::Printf(TEXT("Mesh__%d"), _actor->SerializedComponents.Num()));
	UGeneratedMeshComponent* componentMesh = NewNamedObject<UGeneratedMeshComponent>(_actor, NewName);

	TArray<FVector> points;
	points.Add(FVector(-201, -135, -50));
	points.Add(FVector(-151, -136, -50));
	points.Add(FVector(-121, -137, -50));
	points.Add(FVector(-111, -138, -50));
	points.Add(FVector(-381, -117, -50));
	points.Add(FVector(-371, -136, -50));
	points.Add(FVector(-341, -135, -50));
	points.Add(FVector(-331, -114, -50));
	points.Add(FVector(-321, -113, -50));
	points.Add(FVector(-311, -114, -50));

	TArray<FGeneratedMeshTriangle> triangles;
	ATerrainActor::Lathe(points, triangles, 128);
	componentMesh->SetGeneratedMeshTriangles(triangles);
	componentMesh->bVisible = true;
	componentMesh->bOwnerNoSee = false;
	componentMesh->SetHiddenInGame(false);

	_actor->AddComponent(FName("TerrainMeshComponent"), true, FTransform(FVector()), componentMesh);


I think the missing piece is that you need to call RegisterComponent on the newly created component once you finish setting up its properties.

The AddComponent function you’re calling there is used by the AddComponent blueprint nodes, I don’t think it is really what you want to use in this case.