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

I’m building a character in C++, and I want to have a weapon component which is instantiated from a class which can be set in blueprint. In my .h file I have this to parametrize the class:

/** Weapon class to spawn */
UPROPERTY(EditDefaultsOnly, Category="Weapon")
TSubclassOf<class UWeaponBaseComponent> InitialWeaponClass;

Then in the .cpp I am trying to instantiate like my other components, but it’s throwing an error:

MyCharacter::MyCharacter(const FObjectInitializer& ObjectInitializer):Super(const FObjectInitializer& ObjectInitializer)
    currentWeapon = CreateDefaultSubobject<InitialWeaponClass>(TEXT("InitialWeaponComponent"));

The error I get is No matching function to CreateDefaultSubobject.

So I guess InitialWeaponClass is not a class which can be passed to the template function CreateDefaultSubobject. What’s the right way to do this?

InitialWeaponClass is a member variable not a type name for a function template.

Try non-template version of CreateDefaultSubobject, here is an example:

	UPrimitiveComponent* CurrentWeapon = nullptr;
	TSubclassOf<UPrimitiveComponent> WeaponClass = UStaticMeshComponent::StaticClass();
	CurrentWeapon = Cast<UPrimitiveComponent>(CreateDefaultSubobject(TEXT("InitialWeaponComponent"), *WeaponClass, *WeaponClass, true, false, false));
1 Like

Thanks - doing it this way I’m no longer getting the compiler error. I am getting a runtime error though: it looks like my WeaponClass is still null in the constructor even though I’ve set a default for it in the blueprint.

So I guess the defaults set in blueprint are not available in the constructor? When do they become available, and when is the right time to use them?

Yep, properties are loaded later. Use this: AActor::PostInitProperties | Unreal Engine Documentation