Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why variable is null in Unreal Engine?

I want to call function, which changes the text inside the widget.

There is a virtual function NativeConstruct, which calls automatically. And it changes text of widget, but I need to call function F1 and send a text to it, which I want to display. But when I call it, the variable Name is nullptr. And by some reason, it is not nullptr, when program call NativeConstruct.

  • Name is my text variable, which I want to change
  • dialogBottom is the name of widget with this variable

Edited

UAccessWidgetFromCpp* AccessWidgetFromCpp 
= CreateWidget<UAccessWidgetFromCpp>(
      GetWorld()->GetFirstPlayerController(), UAccessWidgetFromCpp::StaticClass()
   );

if (AccessWidgetFromCpp)
{
   AccessWidgetFromCpp->F1("222");
   widgetDialogBottomInstance->AddToViewport();
}

UCLASS()
class HOME_API UAccessWidgetFromCpp : public UUserWidget
{
   GENERATED_BODY()

public:
   UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
   class UTextBlock* Name = nullptr;

   UFUNCTION()
   void F1(FString text);
};

void UAccessWidgetFromCpp::F1(FString text)
{
   if (auto widget = dynamic_cast<UTextBlock*>(GetWidgetFromName(TEXT("Name"))))
   {
      Name = widget;
      Name->SetText(FText::FromString(text));
   }
}

enter image description here

enter image description here

like image 549
Dima Kozyr Avatar asked Nov 26 '25 10:11

Dima Kozyr


1 Answers

Your UPROPERTY the Name has not initialized to nullptr in the beginning. Therefore, it could contain any garbage value inside it.

Initialize it to nullptr in the class definition or in the constructor of UAccessWidgetFromCpp(if any). For instance, this will fix the issue

UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
class UTextBlock* Name = nullptr;
//                     ^^^^^^^^^^

Regarding the new update:

First of all, you should avoid using c-style casting in C++. Secondly, the function GetWidgetFromName returns, uobject widget corresponding to a given name. Therefore you should be sure about having one with "Name".

Otherwise, make your code safe by double-checking the nullptr scenarios.

if(auto widget = dynamic_cast<UTextBlock*>(GetWidgetFromName(TEXT("Name")))) 
{
    Name = widget;
    Name->SetText(FText::FromString(text));
}

Even now you do not reach the line Name->SetText(FText::FromString(text)); means either you have no widget called "Name" or it is not possible to cast the UWidget* to a UTextBlock*. You might need a redesign of how to do this.

like image 84
JeJo Avatar answered Dec 02 '25 05:12

JeJo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!