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):
AHierarchyActor::AHierarchyActor()
{
PrimaryActorTick.bCanEverTick = false;
mMesh = CreateDefaultSubobject<UProceduralMeshComponent>(TEXT("ProceduralMesh"));
RootComponent = mMesh;
}
void AHierarchyActor::BeginPlay()
{
Super::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?