Download

How to make a button do something in C++

Through game controller class I spawn an actor, create a reference to it and have it follow my cursor. But what I want is to have this action occour once I press a button that I’ve set up with a widget. All the tutorials that I can find are based around bluerprint projects, I’d like this to be done through code. How can I make the button interact with game controller class, or is there a better way to set it up, and how? Thanks!

Hello,

I’m assuming your button is created using UMG.

In that case:

  • First, Override the ‘OnClicked’ event (Scroll at the bottom of the Details panel when selecting your button)
  • And then, from there, you should be able to call any C++ function you want (If you have a reference of the object you want to call the function onto.)

To call a C++ function from Blueprint, you will need to use some Macros. (Placing them before your function declaration in the header)

(You probably want to use BlueprintCallable)

Here is a quick explanation of what the different keyword does:

  • BlueprintPure’ : Will create a Blueprint node without an execution pin
  • BlueprintCallable’ : Will create a Blueprint node with an execution pin
  • ‘**BlueprintImplementableEvent’ : **Will create an Blueprint Event what can be overriden by Blueprint classes children of your C++ class. (*Do not create a C++ implementation or it wont compile)
  • ‘**BlueprintNativeEvent’ **: Same as the Implementable event, but can also have a C++ implementation. In that case, the C++ implementation must have ‘_Implementation’ at the end.

Hi
With UMG:

H:

UPROPERTY(meta = (BindWidget)) UButton* DoneButton;

UFUNCTION() void OnClick();

CPP:
void UMissionCompleteScreen::NativeConstruct() {
Super::NativeConstruct();

if (!DoneButton->OnClicked.IsBound()) DoneButton->OnClicked.AddDynamic(this, &UMissionCompleteScreen::OnClick);   

}

void UMissionCompleteScreen::OnClick() {

}

Hi Telimaktar, thanks for sharing how to bind the function dynamically, can you share me how can you unbind the function, so that if we destroy this object, it won’t create unnecessary errors from removed delegates

Hi

The same but just
DoneButton->OnClicked.RemoveDynamic(this, &UMissionCompleteScreen::OnClick)

https://docs.unrealengine.com/en-us/…egates/Dynamic