Is there a way to access a Blueprint class from C++ in Unreal?

259 Views Asked by At

I would like to be able to access a blueprint class via C++ code. I have the Blueprint class BP_EquipmentBase which is used for items that can be picked up, dropped, and used, and from my C++ player class, I would like to keep an array of held items, and a reference to the currently active item, but in my code, BP_EquipmentBase isn't interpreted as a valid class.

I have tried directly accessing the class by its name, like so:

UPROPERTY(EditAnywhere, BlueprintReadOnly)
BP_EquipmentBase* CurrentItem;

UPROPERTY(EditAnywhere, BlueprintReadOnly)
TArray<BP_EquipmentBase*> HeldEquipment;

which is invalid because it throws the error identifier "BP_EquipmentBase" is undefined. And since that point, I have been stuck trying to figure out how to access it from C++, because a lot of the things I've read told me to make a blank C++ actor class, and make it inherit from that, and use TSubclassOf, but I'm wondering if there's an easier method that doesn't require another C++ class.

1

There are 1 best solutions below

0
Samaursa On

It is possible (and quite common) to access a Blueprint class in code and use the built-in reflection mechanisms to peer into it.

However, what you are attempting to do i.e. have the Blueprint class be a UPROPERTY is not possible. The type of the variable must be known at compile time. You can however use TSubclassOf<UObject> or a UObject* (which assumes you are storing instances).

UPROPERTY(EditAnywhere, BlueprintReadOnly)
UObject* CurrentItem;

UPROPERTY(EditAnywhere, BlueprintReadOnly)
TArray<UObject*> HeldEquipment;

Although now there is no way to cast it to the Blueprint type. However, you can call functions by name by finding the function with the FindFunction(FunctionName) method on the UObject* and, once found, call ProcessEvent.

It will look something like this:

if (UFunction* Function = ObjPtr->FindFunction(FunctionName))
{
    ObjPtr->ProcessEvent(Function, nullptr);
}

With all that said, unless you are writing tooling for Unreal and/or know Unreal's reflection system quite intimately, this is probably not a good idea. You wanted to avoid adding yet another C++ class. I don't think you should avoid it. Define a base class with overridable functions in C++ and then inherit from it.