From within `UserWidget`: get HUD

It looks like I can do

GetGameInstance()->GetPrimaryPlayerController()->GetHUD()

and it seems this works for both, C++ and Blueprint.

Given that my UserWidget is loaded by a HUD in order to be added to the viewport … there should be a way to get the HUD in a more direct way.

But is there?

You could go a different route and just pass it in when creating the widget from code.

MyUserWidget.h

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

#pragma once

#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "MyUserWidget.generated.h"

/**
 * 
 */
UCLASS()
class BALLROLL_API UMyUserWidget : public UUserWidget
{
	GENERATED_BODY()

public:
		
	UPROPERTY(BlueprintReadWrite, Category = "Default", meta = (ExposeOnSpawn = "true"))
		class AMyHUD* Hud;
};

MyUserWidget.cpp is empty

MyHUD.h

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

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/HUD.h"
#include "MyHUD.generated.h"

/**
 * 
 */
UCLASS()
class BALLROLL_API AMyHUD : public AHUD
{
	GENERATED_BODY()
	AMyHUD(const FObjectInitializer& ObjectInitializer);
		
};

MyHUD.cpp

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


#include "MyHUD.h"
#include "MyUserWidget.h"
#include "Engine/World.h"

AMyHUD::AMyHUD(const FObjectInitializer& ObjectInitializer)// : Super(ObjectInitializer)
{
	
	UMyUserWidget* userW = CreateWidget<UMyUserWidget>(GetWorld(), UMyUserWidget::StaticClass(), "Widget");
	if (userW) {
		userW->Hud = this;
		userW->AddToViewport();
	}

}
2 Likes

yep, I am about to implement it like this. I will make a base class “MyUserWidget” that inherits from UUserWidget where I will add the HUD property and I will derive all my user widgets from MyUserWidget.

Still seems odd to me.

Well it’s the most direct approach without jumping around classes. You just contact the reference directly.

How about GetOwningPlayer()->GetHUD() ?

2 Likes