An example I just tried and works with components
Header
UFUNCTION()
void AddComp();
UPROPERTY(BlueprintReadWrite, editAnywhere)
UStaticMesh* MeshTest;
CPP
// added input bind in cpp in SetupPlayerInputComponent
PlayerInputComponent->BindAction("AddComp", IE_Pressed, this, &AmcCharacter::AddComp);
void AmcCharacter::AddComp() {
if (MeshTest != nullptr) {
UStaticMeshComponent* comp = NewObject<UStaticMeshComponent>(this, UStaticMeshComponent::StaticClass(), TEXT("MyComp"));
comp->RegisterComponent();
comp->SetStaticMesh(MeshTest);
comp->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::SnapToTargetNotIncludingScale);
}
}
Yes all NewObjects need to be managed more tightly so you need to destroy them if not needed.
Maybe you need to pass them to a TArray that is a uproperty if they are garbage collected. (I’ve only used NewObject for actors so not sure of their lifecycle)