Right method to spawn component at runtime in 2019

hello am from future, in 4.26.2 the following was done during ::PreInitializeComponents() to create a mesh component thats also visible in properties panel, added some comments for google’s sake:

USkeletalMeshComponent* NewSkeletalMeshComponent = NewObject<USkeletalMeshComponent>(this, USkeletalMeshComponent::StaticClass(), NewMeshCompName, RF_NoFlags, FoundSkeletalMeshComponent); //take note of last argument here, it almost makes a perfect copy of FoundSkeletalMeshComponent, including scale and USkeletalMesh

NewSkeletalMeshComponent->SetupAttachment(GetRootComponent());

NewSkeletalMeshComponent->RegisterComponent();

//NewSkeletalMeshComponent->AttachToComponent(args) this will crash the game, and its redundant as RegisterComponent does an AttachToComponent using data from SetupAttachment!!!

AddInstanceComponent(NewSkeletalMeshComponent); //without this, component wont show up in properties
3 Likes