How to add ActorComponent to Actor?

This crashes the entire IDE! I can’t open it anymore to trial and error it.

#include "MyActor.h"
#include "MyActorComponent.h"

// Sets default values
     // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    UActorComponent* test = CreateDefaultSubobject<UActorComponent>(TEXT("test"));


[FONT=“Helvetica Neue”]

Hi there!

So to attach a component to something, you create a root component first and then you can attach things (like components) to your root from there. I put together some sample code for you as an example. This is code for an Ammo Pickup Item that has a UBoxComponent and a UStaticMeshComponent. Note there are two functions used to attach the components: AttachToComponent() and SetupAttachment(), either of these work and you can read more about them in the ue4 documentation to decide which you would like to use.

// Scene & Root Component
    AmmoSceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("AmmoSceneComponent"));
    RootComponent = AmmoSceneComponent;

    // Create a Static Mesh Component and attach it to the Root Component
    AmmoMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("AmmoMesh"));
    AmmoMesh->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);

    // Create Box Collider and attach it to Root the Component.
    AmmoBoxCollider = CreateDefaultSubobject<UBoxComponent>(TEXT("AmmoBoxCollider"));

Hope this helps and have a lovely day :slight_smile: