Create component from TSubclassOf?

Hello,

I have a class which contains a variable, which is a TSubclassOf, and I’m setting this variable in blueprints. Now, I need to know how to make a component of this specified class

I have an actor component that will be used as a base for some other components, and these other components will be used for their own respective characters. How could I approach this in c++? My current thought is to make a TSubclassOf for my character class, which would then be set to their respective component in blueprints, and from there make a component of that class in c++. But how can I do this??

Thanks in advance :slight_smile:

Stefan

TSubclassOf is just for type safety. Do you mean you have a variable that is base class for a set of components? Is that base class always the same?

Well, I have a base class for each type of component (like inventory comp, status comp, etc.). From those I can create child components in blueprint. What I need is to assign these child component classes to a variable in c++.

Hope that made sense ^.^
Thanks!

Can you not just expose the variable to blueprints

Yes, I am already. This way I can assign my child components to their respective actors, but now the next step is to create them, just like you create components with CreateDefaultSubobjects. But how can I use this assigned component class, and create a default subobject or create component from class??

Thanks :slight_smile:

Something like this maybe?

BaseClass* NewComp = ConstructObject<BaseClass>( ChildClass, this, Name);

I’m sorry, this doesn’t work. Atleast it’s not showing up in the components-hierarchy.

Thanks for the help, appreciate it! :slight_smile:

TSubClassof ChildClass;
BaseClass* = NewObject(this, ChildClass, TEXT(“ChildClass”));

This should work

For .h file
#include

TSubclassOf<MyCustomClass> SelectOnBlueprint;

class MyCustomClass* MySelectedClass

For .cpp file
#include <MyCustomClass.h>

OnBeginPlay()
    {
        if(SelectedOnBlueprint != NULL)
        {
              //Spawn an instance of object SelectedOnBlueprint and assign to MySelectedClass object 
              MySelectedClass = GetWorld()->SpawnActor<SelectedOnBlueprint >(GetClass(), NewLocation, FRotator::ZeroRotator);                                    
    
        }
    }

You can not use SpawnActor for a component.

To create a component at runtime you need to call NewObject

MyComponent = NewObject(this, MyComponentsClass);
if (MyComponent)
{
   //Setup attachement here

   //This will register the component with the actor supplied in the Outer (the 'this' in the NewObject.
   MyComponent->RegisterComponent();
}

where MyComponentClass is your TSubclassOf.