Download

Add blueprint actor component to character made in C++

As I am very new to C++ dev in Unreal Engine, I am stuck with a normally simple task. I have a Character Pawn (“StealthCharacter”) made in C++ with some movement and I have a blueprint of some behaviour (“Detector”) that needs to be attached to it.

After some search, I tried to include it like this in the header:



class SOMEGAME_API AStealthCharacter : public ACharacter
{
    GENERATED_BODY()

        UPROPERTY(EditAnywhere, Category="Detector")
        TSubclassOf<UActorComponent> mainDetector;

        ...
}


but I don’t know how to continue from here.

If you want to add in C++ an actor component to your character, you can proceed as follows:

  • in the header file of your character class, create an attribute to hold your component:


    UPROPERTY(BlueprintReadOnly, Category = Setup)
        UMyComponent *MyComponent = nullptr;


  • in the constructor of your character, you create the component dynamically:


AMyCharacter::AMyCharacter(const FObjectInitializer& ObjectInitializer)
    : Super(ObjectInitializer)
{
    MyComponent = CreateDefaultSubobject<UMyComponent>(FName("My Component"));
}


Note that if your component is a blueprint only, you may first need to create a C++ base class for this blueprint then reparent the blueprint.