Create custom widget and add to viewport in C++

You cretare UClass* varable WidgetClass but you never set it, when it reach CreateWidget WidgetClass is still not set, function don’t know which widget you want to make, the class in template i just for auto casting and it ignored in widget spawning if you put class argument. So function fails to create widget as result WidgetClass is null and when you call your function you calling it on null pointer, which means immediate crash. So replace:

TSubclassOf<class UUserWidget> WidgetClass;
UErrorWidget* ErrorWidget = CreateWidget<UErrorWidget>(GameInstance, WidgetClass);

with single line of this:

UErrorWidget* ErrorWidget = CreateWidget<UErrorWidget>(GameInstance, UErrorWidget::StaticClass());

You can try not placing class argument since template will do that for you, it works with SpawnActor not sure if this function has same set up it might not work:

UErrorWidget* ErrorWidget = CreateWidget<UErrorWidget>(GameInstance);

The reason why CreateWidget fail is most likely printed in log, so always check logs (in Saved/Logs in project directory) if you have crash. Also since CreateWidget don’t gurranty sucess you should make:

if(ErrorWidget) {
     ErrorWidget->setErrorMessage(ErrorMessage);
     ErrorWidget->AddToViewport();
}

This will prevent crash from happening if CreateWidget fails, or else you want it to crash when it fails.

Also CreateWidget wants PlayerController not GameInstance, or else API reference missing this overload

http://api.unrealengine.com/INT/API/Runtime/UMG/Blueprint/CreateWidget/1/

there also other function you may try:

http://api.unrealengine.com/INT/API/Runtime/UMG/Blueprint/UUserWidget/CreateWidgetOfClass/index.html

1 Like