Hi, so I’m in the process of learning Unreal by prototyping a basic game completely through C++, and I was researching how to implement a basic UI/HUD. Pretty much every guide and tutorial at some point used Blueprints to bind functionality to the custom UserWidget, and while I’ll probably have to do that, I was wondering if there was any way to completely just write it in code?
Right now, I’m just trying to make a basic scoring system where a TextBox will just uptick by 1 every time a specific collision occurs. I know there’s meta=(BindWidget()), but nothing tells me how to change the value once a FText (converted from int to FString to FText) is binded.
Also, minor side question: I assume I should keep all scoring logic out of the widget? I once tried to control the score through the widget, but it both did not work and consistently crashed Unreal. I relocated all the logic to the gamemode for now.
Create a C++ class that is a child of UUserWidget. (Let’s call it “MyWidget”.)
In the Editor, create a UserWidget class in Blueprint (let’s call it “BP_MyWidget”). Open BP_MyWidget, and in the Class Settings, re-parent to make it a child of MyWidget.
In BP_MyWidget, in the Designer tab, lay out the design of your widget and create a TextBox where desired. (Let’s call it “MyTextBox”.) Make it a variable.
In MyWidget.h, add the following:
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
UTextBlock* MyTextBox;
Very important: The name of the text box needs to be the same in the BP_MyWidget class as it is in the MyWidget.h file.
Also, in your MyWidget.h file, make sure to forward declare the class UTextBlock.
In the .cpp file, when you want to update the text in the TextBox to reflect the new score using an FText (let’s call it “MyFText”), do it as follows:
MyTextBlock->SetText(MyFText);
Also, in your MyWidget.cpp file, make sure to include Components/TextBlock.h
If you want to program your UI completely in C++ I suggest you to use Slate. It’s the UI framework that powers Unreal Engine 4 editor and the UMG widgets are just UObjects that wrap Slate native widgets.
If you use Slate of course you’ll have better performance, but I prefer UMG because there is an WYSIWYG designer and you don’t have to recompile your game module everytime you want to see changes in your UI, so keep in mind you’ll have slower iteration times if you go with Slate.