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

**URL:** <https://forums.unrealengine.com/t/what-is-the-correct-way-to-create-and-add-components-at-runtime/15605>\
**Category:** C++\
**Tags:** unreal-engine\
**Created:** [November 20, 2014, 5:40pm UTC](https://forums.unrealengine.com/t/what-is-the-correct-way-to-create-and-add-components-at-runtime/15605 "2014-11-20T17:40:42Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![asmrpuppy](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@asmrpuppy](https://forums.unrealengine.com/u/asmrpuppy)\
**Post date:** [August 15, 2015, 12:09am UTC](https://forums.unrealengine.com/t/what-is-the-correct-way-to-create-and-add-components-at-runtime/15605/8 "2015-08-15T00:09:53Z")

</div>

> [@Rama;182878](#):
>
> **Creating and Registering Components During Runtime**
> 
> ```auto
> 
> //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
> 
> ```auto
> 
> 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 🙂
> 
> ```auto
> 
> 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
> 
> ```

Rama, thank you so much for this! This post here is golden.

It was the straw that broke the camel’s back that got my physics system working.

Thank you a million, again.

---

_[View the full topic](https://forums.unrealengine.com/t/what-is-the-correct-way-to-create-and-add-components-at-runtime/15605)._
