I got my button visible on screen by moving this code from NativeConstruct to Initialize function. But after recompile i am getting CanvasPanel is not packaged exception and crash on hot-reload.
// Initialize called after hot-reload with WidgetTree = NULL, skip this unexpected call, or you will get CanvasPanel is not packaged error.
if(WidgetTree)
{
auto MyCanvas = WidgetTree->ConstructWidget<UCanvasPanel>(UCanvasPanel::StaticClass());
auto MyButton = WidgetTree->ConstructWidget<UButton>(UButton::StaticClass());
MyCanvas->AddChildToCanvas(MyButton);
WidgetTree->RootWidget = MyCanvas;
}
}
Well, now i got UMG widget constructed and visible, but i dont know yet how to do that AFTER Initialize call, for instance inside NativeConstruct function, which is called after Initialize.
Iβve got it working dinamically, but i still have to set WidgetTree->RootWidget = MyCanvas inside Initialize function:
bool UMyUserWidget::Initialize()
{
bool b = Super::Initialize();
// more correct way to avoid error. than in original post.
if(!HasAnyFlags(RF_ClassDefaultObject) )
{
// root have to be initialized in Initialize function, otherwise it will not work, donno exactly why.
MyCanvas = WidgetTree->ConstructWidget<UCanvasPanel>();
WidgetTree->RootWidget = MyCanvas;
}
return b;
}
void UMyUserWidget::NativeConstruct()
{
Super::NativeConstruct();
auto MyButton = WidgetTree->ConstructWidget<UButton>();
MyCanvas->AddChildToCanvas(MyButton);
}