How does Widget blueprint bind work in C++?


In widget blueprint, we can just make blueprint scripting to dynamically bind some values to UMG real time. But how does this work in C++?

If we make UWidget class and use UPROPERTY(meta = (BindWidget)) to bind c++ variable to UMG in widget blueprint, don’t we have to make refresh function and call it every time we want it to change?
How does blueprint know if the values changed or not and automatically refreshes it?

In C++, you can bind a function to a widget event using the BindUFunction method. This method creates a delegate that points to a member function of the owning class that matches the signature of the event. Here’s an example of how to use it:

// Declare a delegate signature that matches the OnClicked event
DECLARE_DELEGATE(FOnButtonClicked);

class UMyWidget : public UUserWidget
{
public:
// Declare a delegate instance that will be used to bind a function to the OnClicked event
FOnButtonClicked OnButtonClicked;

// Call this function to bind a member function to the OnClicked event
void BindButtonClicked(UButton* Button)
{
    if (Button != nullptr)
    {
        Button->OnClicked.AddDynamic(this, &UMyWidget::HandleButtonClicked);
    }
}

// Member function that will be called when the OnClicked event is raised
UFUNCTION()
void HandleButtonClicked()
{
    // Do something in response to the button being clicked
}

};

In this example, we declare a delegate FOnButtonClicked that matches the signature of the OnClicked event of a button widget. We also declare an instance of this delegate OnButtonClicked in the widget class. To bind a member function to the button’s OnClicked event, we call the AddDynamic method on the button, passing in this (a pointer to the widget instance) and a pointer to the member function we want to bind (&UMyWidget::HandleButtonClicked).

When the button is clicked, the HandleButtonClicked member function of the widget will be called, allowing us to respond to the event in code.

Okay but what do we do about binding just text UI or progress bar?

For example, we have current score on user’s widget hud and making it display current_score variable stored in GameMode class.

In this case I should make widget refreshing function and bind it to score increase function in GameMode right?

The blueprint binding function seems to be called every frame update and if the function gets to complicated I think it could be bad for my game performance.