How to create a custom UActorComponent properly?

Hi all,

I have the following code in .H:

UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Custom Actor Components")
class UMyActorComponent* MyActorComponent;

and in the constructor of .CPP:

MyActorComponent = CreateDefaultSubobject<UMyActorComponent>(TEXT("MyActorComponent "));

The MyActorComponent pointer is not initialized. WHY???

Hello! it’s like that:


UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Custom Actor Components")
class UActorComponent* MyActorComponent;


MyActorComponent = CreateDefaultSubobject<UActorComponent>(TEXT("MyActorComponent "));

includes the library in the .cpp:

#include "Components/ActorComponent.h"

you are typing the name of your class in the class type! do not forget to mark the answer as correct

Thank you for your answer, but I need to create my custom actor component (UMyActorComponent), not UActorComponent. It seems you are creating UActorComponent. UMyActorComponent is a child of UActorComponent.

so first you need to create an ActorComponent class that derives from UActorComponent. Then you can add this newly created ActorComponent to your actor.

I know that I can have my custom component deriving from UActorComponent and then I can add it manually to a an AActor BP, but how to do that in C++ only? I mean creating like other components in UE4 with using CreateDefaultSubobject.