Use Blueprint asset as a type in C++

I have an ActorComponent with a C++ base (MyComponent) and a BP that inherits from it (BP_MyComponent).

I’d like to be able to instantiate a BP_MyComponent in C++ on my Actor, and then in my Blueprint graph in my Actor, be able to reference that same object.

I’ve managed to mostly solve this problem, by using a TSubclassOf<MyComponent> MyComponentClass, setting it to BP_MyComponent in the editor, then calling MyComponentProperty = NewObject(MyComponentClass) from MyActor::PostInitProperties().

The issue with this is that the type of MyComponentProperty is still the base C++ class MyComponent, meaning I need to cast & narrow it to BP_MyComponent every time I want to use it from blueprints. Alternatively I can create a separate variable in my Actor blueprint so I can cast it once (immediately after PostInitProperties) but then I’m forced to use a different variable name, which I’d really like to avoid.

I’m guessing there aren’t many other options here but thought I’d ask anyway, since this seems like something that people would somewhat commonly want to do.

You can’t. Types is C++ are only used for compilation checks and calculating memory offsets to access variables. After compilation (machine code), everything becomes memory offsets and types do not exist anymore. Blueprint stuff does not exist at compile time, everything is generated dynamically at runtime.

What you did is definitely the right way to go. If you want to spawn a blueprint from C++, define a TSubclassOf variable and set it in child BP. Then yes your reference will be of the native type and you’ll have to cast it.

If the functions/variables declared in BP_MyComponent are so important that you always have to cast from your native MyComponent variable, why not instead declare those variables/functions (or at least stubs) in the native MyComponent class ? Then no need to cast anymore.

1 Like