What is the correct way to create and add components at runtime ?

Creating and Registering Components During Runtime



//in some AActor class

void AYourActor::CreateComponent(UClass* CompClass,const FVector& Location, const FRotator& Rotation, const FName& AttachSocket=NAME_None)
{
  FName YourObjectName("Hiiii");

  //CompClass can be a BP
  UPrimitiveComponent* NewComp = ConstructObject<UPrimitiveComponent>( CompClass, this, YourObjectName);
  if(!NewComp) 
 {
    return NULL;
 }
 //~~~~~~~~~~~~~

  NewComp->RegisterComponent();        //You must ConstructObject with a valid Outer that has world, see above	 
  NewComp->SetWorldLocation(Location); 
  NewComp->SetWorldRotation(Rotation); 
  NewComp->AttachTo(GetRootComponent(),SocketName,EAttachLocation::KeepWorldPosition); 
   //could use different than Root Comp
}


The most notable line is this



UPrimitiveComponent* NewComp = ConstructObject<UPrimitiveComponent>( CompClass, this, YourObjectName);


in this case, “this” is the owning Actor that is creating its own component, and I am passing in “this” to ConstructObject

NewComp->RegisterComponent() will not work unless “this” is valid and has a valid world associated with itself, as most AActors will :slight_smile:


Attach Location

Keep in mind you could use SnapToTarget or KeepRelativePosition

I am choosing here to specify world space starting location and THEN attach.

You could always use Root Comp or add parameter to specify which component to attach to.

You'll probably want to use "Mesh" for any Character :)

It's up to you!

Enjoy!

Rama
5 Likes