Proper way to spawn a Component at Runtime?

A component (“MyOuterComponent”) spawns multiple other components (“MySubComponent”). MySubComponent has its own UStaticMeshComponent (among other things - there’s a reason for all this madness!)

However, for whatever reason, MySubComponent spawns multiple StaticMeshComponents, which it shouldn’t:

211352-bug-2b.png

MyOuterComponent has code that looks like this:

void UMyComponent::GeneratePiece(...)
{
	UMySubComponent* NewSubComponent = NewObject<UMySubComponent>(this->GetOwner(), UMySubComponent::StaticClass(), FName(...));

	NewSubComponent->RegisterComponent();
	NewSubComponent->AttachTo(this);

	...
}

Meanwhile MySubComponent looks like this:

UMySubComponent::UMySubComponent()
{
	PrimaryComponentTick.bCanEverTick = false;

	PieceMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Piece"));
	PieceMesh->SetupAttachment(this);

	...
}

Solution: All the UStaticMeshComponents attached to the spawned MySubComponent had the same name. Given each mesh a unique name fixed the problem.

Solution: All the UStaticMeshComponents attached to the spawned MySubComponent had the same name. Giving each mesh a unique name fixed the problem - only one piece was spawned per sub-component, and each sub-component had a piece (previously, some sub-components didn’t get one.)