my root widget slot is null

I created a c++ class based on umg and i want to add a text block to it . first i get the root widget and check that if it is null add a root widget but when i want to cast slot of my root widget , the slot is null and my cast fails . also i tried adding manually a root component to Blueprint of my c++ widget and my text block wont appear in hierarchy .

TSharedRef UW_Player::RebuildWidget()
{

UPanelWidget* RootWidget = Cast<UPanelWidget>(GetRootWidget());



if (!RootWidget)
{
	RootWidget = WidgetTree->ConstructWidget<UCanvasPanel>(UCanvasPanel::StaticClass(), TEXT("RootWidget"));

	UCanvasPanelSlot* RootWidgetSlot = Cast<UCanvasPanelSlot>(RootWidget->Slot);//Slot Is Null 
	if (RootWidgetSlot)
	{
		RootWidgetSlot->SetAnchors(FAnchors(0.0f, 0.0f, 1.0f, 1.0f));
		RootWidgetSlot->SetOffsets(FMargin(0.0f, 0.0f));

	}

	WidgetTree->RootWidget = RootWidget;

}



TSharedRef<SWidget> Widget = Super::RebuildWidget();



if (RootWidget && WidgetTree)
{
	HealthText = WidgetTree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass(), TEXT("HealthText"));

	RootWidget->AddChild(HealthText);
	UCanvasPanelSlot* HealthTextSlot = Cast<UCanvasPanelSlot>(HealthText->Slot);
	if (HealthTextSlot)	
	{
		HealthTextSlot->SetAutoSize(true);

	}

}

return Widget;

}

1 Like