Instantiate a UActorComponent from a parametrized class in C++?

Hello All!

I’m building an obstacles handler in C++.
I want to have the obstacle component which is instantiated from a class that can be set in blueprint.
In my .h file I have this to parametrize the class:

UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf<UChildActorComponent> ObstacleComponent = UStaticMeshComponent::StaticClass();

Then, I’m trying to instantiate the component like this:

UChildActorComponent* Component = NewObject<UChildActorComponent>(Plateform, *ObstacleComponent );

I’m trying to do the same as the following topic: Instantiate a UActorComponent subclass from a parametrized class in C++?
But, the answer given seems depreciated (it doesn’t work)

Anyone has an idea?

Thank you in advance!

First of all, is your obstacle handler component really a child of child actor component? That seems a bit wrong. I would guess it’s a child of UActorComponent. Either way, if you do have a parent C++ class for your obstacle handler, let’s call it UObstacleHandlingComponent, then your code would look something like this:

UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf<UObstacleHandlingComponent> ObstacleComponentClass;

UObstacleHandlingComponent* ObstacleHandlingComponent;

Then in your code, which would probably have to be on begin play, because you can’t use the value of a property in your constructor as far as I know, you would do something like:

// Instead of If you could also do a check, since I'm guessing this should never be null
if (ObstacleComponentClass)
    ObstacleHandlingComponent = NewObject<UObstacleHandlingComponent>(this, ObstacleComponentClass);
    // Throw some error

This is not a subclass (“child class”) of:

The UChildActorComponent is a UActorComponent subclass that lets you attach an AActor to another AActor.
UStaticMeshComponent is a subclass of UActorComponent.
(And USceneComponent, and UPrimitiveComponent, and UMeshComponent in turn)

In general, “child” means scene attachment hierarchy, whereas “subclass” means class hierarchy. Those are different concepts. TSubclassOf<> works with the C++ class hierarchy.

1 Like

Thanks @jwatte, you pointed out my mistake.
So, the solution is this one (I use a USceneComponent now) :

// header
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Infinity Ground")
TSubclassOf<USceneComponent> Component = UStaticMeshComponent::StaticClass();
// cpp
USceneComponent* StaticMeshComponent = NewObject<USceneComponent>(Plateform, Component);

Thanks too @zeaf , I also need to check the nullptr value. I confirm I use NewObject because I’m after BeginPlay.