Here’s a templated version of loading a blueprint from C++. Used only for loading HUD blueprints, so in this case it is in our AHUD class .h file.
Example of use:
_toolbarHudWidget = LoadHUDWidget<UPrimaryToolbarHUDWidget>(GetWorld(), "/Game/Blueprints/HUD/PrimaryToolbar.PrimaryToolbar_C"); // append _C
Code must be in .h file since it is a template function.
template<typename T = UUserWidget, typename Owner = UObject>
static T* LoadHUDWidget(Owner owningObject, FString widgetName)
{
// load the HUD bluprint and add to viewport
FSoftClassPath HUDClassReference(widgetName); // must append "_C"!!!
UClass* HUDClass = HUDClassReference.TryLoadClass<UUserWidget>();
if (HUDClass != nullptr)
{
// load the blueprint and add it to the viewport
UUserWidget* tempWidget = CreateWidget<UUserWidget>(owningObject, HUDClass);
T* UserWidgetClass = Cast<T>(tempWidget);
if (UserWidgetClass != nullptr)
{
UserWidgetClass->AddToViewport();
return UserWidgetClass;
}
else
{
LOG("BaseHUD::LoadHUDWidget() - failed for '%s'!", *widgetName);
return nullptr;
}
}
else
{
LOG("BaseHUD::LoadHUDWidget() - failed for '%s'!", *widgetName);
return nullptr;
}
}