How to instanstiate a UMG Button

Hi this code is giving me errors.

The class is extends of is UUserWidget.


	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widgets")
		TSubclassOf<class UButton> PlayButton;

	// Variable to hold the UButton After Creating it.
	UButton* PlayButton;



The idea is that I drop a button in the UI editor, and the add an event listener to PlayButton in the code.

How do I get a reference to this baby?

UButton* playButton = (UButton*)GetWidgetFromName(TEXT(“PlayButton”));
playButton->OnClicked.AddDynamic(this, &UMainMenuUICPP::Test);

Crashes the engine and corrupts project

// Fill out your copyright notice in the Description page of Project Settings.

#include “MyProject.h”
#include “MainMenuUICPP.h”

void UMainMenuUICPP::Construct_Implementation()
{
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT(“This is an on screen message!”));
}

UMainMenuUICPP::UMainMenuUICPP(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
UButton* playButton = (UButton*)GetWidgetFromName(TEXT(“PlayButton”));
playButton->OnClicked.AddDynamic(this, &UMainMenuUICPP::Test);

}

void UMainMenuUICPP::Test()
{
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT(“This is an on screen message!”));

}

Could you use C++ casts instead, I also think UE4 has it’s own casting templates.
You are also not checking to see if playButton is a valid pointer.

Attaching VS to the editor and then pressing “Play” should give you a good idea of what is happening when/if something goes wrong as VS will show you where it (thinks) the error happens.

HTH

You should drop the TSubclassOf<class UButton> member variable as that is only necessary if you want to create the button in c++. Also, careful with the way you have named your variables. Both the TSubclassOf<class UButton> and the UButton* are named PlayButton in your code and that will definitely cause errors.


UButton* playButton = (UButton*)GetWidgetFromName(TEXT("PlayButton"));

This line of code will only be valid after the widget is Constructed. This has nothing to do with the c++ constructor. It is a term used by UMG that means that the underlying slate makeup of the UWidget is created. Once this occurs, all widgets exist in code and are available to be referenced.

This means that it will always fail in the default constructor, because the actual widget itself has not been created yet.

Move the code out of the constructor and into NativeConstruct.

It is also possible to expose the UButton pointer to Blueprint and set a reference to it in the widget blueprint instead of just referencing the widget by name.