Crash on CreateWidget and ConstructWidget

I have a class UAbilityWidget that extends UUserWidget. Then I have a class called UAbilitiesTree which also inherits from UUserWidget.

So I want to create UAbilityWidgets and add them to a canvas procedurally on UAbilitiesTree’s NativeConstruct. So I tried CreateWidget and widgetTree->ConstructWidget and both crash after being executed (take a look at the callstack below).

Here’s my code:



    for (int i = 0; i < abilities.Num(); i++)
    {
        UAbilityWidget* widget = WidgetTree->ConstructWidget<UAbilityWidget>(UAbilityWidget::StaticClass(), FName::FName(*("AbilityWidget" + FString::FromInt(i) + "]")));
        //Also tried CreateWidget<UAbilityWidget>(canvas, UAbilityWidget::StaticClass());

        abilityWidgets.Add(widget);

        UCanvasPanelSlot* slot = canvas->AddChildToCanvas(widget);
    }


Any ideas? Thanks for any help!

[SPOILER]
Callstack:



Access violation - code c0000005 (first/second chance not available)

UE4Editor_UMG!UWidgetTree::ForEachWidget() [d:\build\++ue4\sync\engine\source\runtime\umg\private\widgettree.cpp:123]
UE4Editor_UMG!UUserWidget::GetSlotNames() [d:\build\++ue4\sync\engine\source\runtime\umg\private\userwidget.cpp:938]
UE4Editor_UMG!INamedSlotInterface::SetNamedSlotDesignerFlags() [d:\build\++ue4\sync\engine\source\runtime\umg\private\components
amedslotinterface.cpp:50]
UE4Editor_UMG!UUserWidget::SetDesignerFlags() [d:\build\++ue4\sync\engine\source\runtime\umg\private\userwidget.cpp:1307]
UE4Editor_UMG!UUserWidget::Initialize() [d:\build\++ue4\sync\engine\source\runtime\umg\private\userwidget.cpp:376]
UE4Editor_UMG!UUserWidget::CreateInstanceInternal() [d:\build\++ue4\sync\engine\source\runtime\umg\private\userwidget.cpp:2109]
UE4Editor_UMG!UUserWidget::CreateWidgetInstance() [d:\build\++ue4\sync\engine\source\runtime\umg\private\userwidget.cpp:1975]
UE4Editor_UMG!UUserWidget::CreateWidgetInstance() [d:\build\++ue4\sync\engine\source\runtime\umg\private\userwidget.cpp:1992]
UE4Editor_Hivaneph!CreateWidget<UUserWidget,UWidgetTree>() [c:\program files\epic games\ue_4.21\engine\source\runtime\umg\public\blueprint\userwidget.h:1279]
UE4Editor_Hivaneph!UAbilitiesTreeWidget::NativeConstruct() [c:\users\dev-projects\ue4\hivaneph\hivaneph\source\hivaneph\ui\abilitiestreewidget.cpp:71]


[/SPOILER]

Ok so apparently the first parameter in CreateWidget (OwningObject) has to be the world in which you want to create the widget. So


UAbilityWidget* widget = CreateWidget<UAbilityWidget>(GetWorld(), abilityWidgetClass);

did the trick.

Just as a general practice rule - you should really use the Player Controller that should own (or is displaying) that widget, rather than creating it using a world reference.

CreateWidget<USomeWidget>(GetPlayerController(), WidgetClass)

Hello. Can you give an advice, how to create widget in Editor? PlayerController doesn’t exist while I am editing blueprint, but using parent widget causes crash.