UE4 C++ Hint 1: Constructing / loading an object from a blueprint located in a specific directory

The Issue

You need a way to load a specific Blueprint of any class directly from a file path in C++. Unreal has you covered:

The solution

static ConstructorHelpers::FObjectFinder<UClass> ObjectBP(TEXT("WidgetBlueprint'/Game/Blueprints/HUD/BP_IGC_TimerBarWidget.BP_IGC_TimerBarWidget_C'"));
if (ObjectBP.Object != NULL)
{
// Set the object as the blueprint at the reference above.
SetWidget(ObjectBP.Object);
}

A few important notes!!

This function should only be used in your classes constructor! Anywhere else causes a crash!

It may seem that you should set the type to the object type e.g. <UYourObjectType> but use UClass instead.

The _C in the file path is a specific required tag that is appended to the actual file path only in code.

To be clear the actual file path is:  (WidgetBlueprint’/Game/Blueprints/HUD/BP_IGC_TimerBarWidget.BP_IGC_TimerBarWidget’).

If you want the actual object you need to call .Object.

When to use it

This is usually best to use when:

The file name or location won’t change, if the file can’t be found, issues ahoy!

The object needs to be set during the construction of the object for example, you have a UWidgetComponent that needs to have a UUserWidget class set from a BP but it needs to be set as soon as the WidgetComponent is created.

Hope you guys find this useful!

Categories: