Access BP variable in C++

Hey, I am New to Unreal Engine 4,
Is there a way to read BP variable inside C++ code ?
for example I created a int32 variable in BP and I want to read this in C++ how can I do that ?

Yes you can, but need other way of implementation. Create first that variable in the C++ and expose it in BP.

There’s ways to do it through reflection, but isn’t really documented because it’s “unsafe code” you have to be very confident that you won’t blow up everything…

It’s much safer to just declare the variables in C++ base class.

Assuming you have a reference to the Blueprint class where this variable is defined and a reference to the Blueprint instance of this class, you can do this:



UIntProperty* IntProperty = FindFieldChecked<UIntProperty>(BlueprintClass, TEXT("VarName"));
int32 VarValue = IntProperty->GetPropertyValue_InContainer(BlueprintInstance);


FindFieldChecked will trigger an assertion if the variable does not exist.

Anyway if you have a base class defined in C++ it’s better to define that variable inside the native class, as other members already pointed out.

Thank you very much,

doesn’t “TSubclassOf” save the blueprint of the class, can’t we just use it to get any declared variable in blueprints ?

If you have a reference to the Blueprint instance where you want to read the variable value I think you can just use BlueprintInstance->GetClass()

This works but easily breaks: if you change the variable name in blueprint, you also need to change the name in C++. This is cool functionality though, I didn’t know it before.

As you’re new to Unreal, I assume you want the “standard” solution. Do what Jimmy_Jump said. In code:



UCLASS(Blueprintable) // so you can inherit from this class in BP
class FOOPROJECT_API AFooBase : public AActor
{
GENERATED_BODY()
public:

// BlueprintReadWrite allows blueprint to read and write to property
UPROPERTY(BlueprintReadWrite, Category = "Foo")
int32 FooProperty;

FORCEINLINE int32 GetBar() const 
{
    return BarProperty;
}

private:

// same as foo, only that BarProperty is private in C++. You need the meta part otherwise the UHT complains
UPROPERTY(BlueprintReadWrite, Category = "Bar", meta = (AllowPrivateAccess = "true")) 
int32 BarProperty;

}


In Blueprints, you can just inherit from AFooBase. Now in C++, you could do:



const AFooBase* myFooAsBlueprint = ...; // Somehow get a reference to the blueprint
int32 foo = myFooAsBlueprint->FooProperty;
int32 bar = myFooAsBlueprint->GetBar();


In general, you should prefer the private way because it encapsulates the property in C++.

Thank you all for this great help