Right method to spawn component at runtime in 2019

Need to add to my “ownedActor” StaticMeshComponent and SkeletalMeshComponent. Tried this

		UStaticMeshComponent *NewComp = ownerActor -> CreateDefaultSubobject <UStaticMeshComponent> (name);
				
		ownerActor -> AddOwnedComponent (Cast<UActorComponent>(NewComp));

It was compiled, but then crash… What is the right way to add component UE4.21

Hey, there is lot of question about this, but here is a code snippet :slight_smile:

 USceneComponent* createdComp = NewObject<USceneComponent>(YourComponentsActualClass, this, YourComponentsAddedName);
2. if(createdComp)
3. {
4.     createdComp->RegisterComponent();
5.     createdComp->AttachTo(GetRootComponent(), NAME_None);
6. }

where this is the owner of the new component ^^
cheers

tried this for UActorComponent and didn’t get result for both skinned and static mesh
UActorComponent* NewComp = NewObject (UStaticMeshComponent,ownerActor, name);
but got it with your method by dividing into too functions, THANKS!

Hi, I have tried that, work fine (creates the components and registers it) but it doesnt ever show that component in the editors panel (in v.4.21.2). Do you know any way to make it visible?

In case anyone else reads this, if you are spawning a non-scene component and can’t Attach, you need to call

MyActor->AddInstanceComponent(NewComponent) 

for it to appear in the details view and avoid garbage collection.

details view? you mean the components view section?
also, if it is already registered, shouldn’t it already be safe from being garbage collected?

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
2 Likes

This one works for me!

I am using a different NewObject, a bit easier:

SplineMesh = NewObject<USplineMeshComponent>(this, TEXT("MySplineMesh"));