Pointer to Class Type to initialize CreateDefaultSubobject

How can I use a stored UClass type to initialize an object?

E.g. to do something like this:



TSubclassOf<class UShapeComponent> shapeType;

UShapeComponent* newComponent = CreateDefaultSubobject<shapeClass>("SomeComponent");


(basically, I want to not have to specify the shape type, to accept both sphere and box shapes)
I looks pretty simple but I can’t figure it out.

Hey GuilhermeB,

I’m just going off of memory, but I think it’s something like this.


TSubclassOf<class UShapeComponent> shapeType;

UShapeComponent* newComponent = CreateDefaultSubobject<**shapeClass->GetClass()**>("SomeComponent");

Use the non-templated version of the function:


UObject* CreateDefaultSubobject(FName SubobjectFName, UClass* ReturnType, UClass* ClassToCreateByDefault, bool bIsRequired, bool bAbstract, bool bIsTransient);

1 Like

Assuming you want to be able to set your uclass variable in blueprint, it’s not possible to do this with default subobjects. They’re created too early in the initialization process.

The only way around it is to create the object later using NewObject. Either in something like BeginPlay, or if you need it to exist in editor, using the EditInlineNew/Instanced approach.