How to attach a ProceduralMeshComponent to another ProceduralMeshComponent

Just for testing purposes I’m trying to create a cube at runtime and to attach it to another cube, so that the second cube becomes child of the first one.

The code looks like this (the class extends AActor class):

	PrimaryActorTick.bCanEverTick = false;

	mMesh = CreateDefaultSubobject<UProceduralMeshComponent>(TEXT("ProceduralMesh"));

	RootComponent = mMesh;

void AHierarchyActor::BeginPlay()

	TArray<FVector> vertices;
	TArray<int32> indices;
	TArray<FVector> normals;
	TArray<FVector2D> uvs;
        TArray<FVector> vertexColors;
	TArray<FProcMeshTangent> tangents;

        // Filling the arrays with the info to create the cube
	UKismetProceduralMeshLibrary::GenerateBoxMesh(FVector(20, 20, 20), vertices, indices, normals, uvs, tangents);

        // Creating the first cube
	mMesh->CreateMeshSection(0, vertices, indices, normals, uvs, vertexColors, tangents, false);

        // Creating the second cube object
	UProceduralMeshComponent* mesh = NewNamedObject<UProceduralMeshComponent>(this, TEXT("ProceduralMesh"));

        // Creating the second cube
	mesh->CreateMeshSection(0, vertices, indices, normals, uvs, mVertexColors[0], tangents, false);

        // Shifting the cube a bit just so that they don't overlap
	mesh->SetWorldLocation(this->GetActorLocation() - FVector(1, 1, 1));

        // Attaching the second cube to the first one
	mesh->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);

The code compiles and runs fine, but nothing happens. I see the first cube just fine, but the second one isn’t there at all. What am I doing wrong?

Quick update: I managed to get it working by adding this at the end:


Still, since I’m new to UE4 I’d like to know if this is a proper way of attaching components at runtime or not :slight_smile:

Yes, this way is correct. You have to call RegisterComponent to make sure the component is actually ticked/displayed. I think this is done so you can edit the component between its creation and the actual use.

See Components | Unreal Engine Documentation for more information.