How to add and remove a Box Collision Component in C++?

In The Declaration class definition file (.h)



UBoxComponent* CollisionMesh = nullptr;


In The constructor class definition file (.cpp) :



CollisionMesh = CreateDefaultSubobject<UBoxComponent>(FName("Collision Mesh"));


If you need to put it at the top hierarchy:



SetRootComponent(CollisionMesh);


If you need add other child component like particle system :



Blast = CreateDefaultSubobject<UParticleSystemComponent>(FName("BlastExplosion"));
Blast->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform); // since 4.12 isn't AttachTo(1arg) anymore, but AttachToComponent(2args)


CreateDefaultSubobject works only in constructor. Everywhere else use NewObject.

3 Likes