C++ add component by class using a variable?

Hello! So basically I’m in need of a function that creates a component using a class. I know CreateDefaultSubobject<>() works but I can’t get it working for a variable class reference.
For example:

UClass* AnyClass = BasicallyAnyClass;
CreateDefaultSubobject<AnyClass>(ComponentName);

I need this because I’m working on a function that needs to be able to create components dynamically using their class as a base. How can I do this? Please explain in detail and clearly. Thanks!

You can always do like

AnyClass* Variable = CreateDefaultSubobject<AnyClass>(TEXT("ElClassico"))

My bad, I shouldve been more specific. Basically I want to be able to add a component without really knowing which class it is.

Something wrong with your design.

I fixed the example, I still have the problem it’s just I forgot to type a bit of the code.
Also when I mean any class, I mean it depends on the game, I’m making a loading system and I want to be able to add components to an actor depending on the save file so if a static mesh component was saved, then it will add the static mesh component, if a box collision, then a box collision and so on. Hope this clarifies.

I Solved it! I used the AddComponent() Function.
Here’s an example:

UActorComponent* Component = Actor->AddComponent(ComponentName, false, Transform, ComponentClass);
1 Like