UE4 C++ Getting a reference to HUDClass after it has been initialized

2.8k views Asked by At

In my Game Mode Base class I create an object that is assigned to HUDClass. The HUD works properly but then I cannot seem to access any of its member functions that require sending code back. I have tried absolutely everything at this point and am completely stuck. It seems whatever I do the pointer to the object seems to become NULL. I am using UE4.25.3.

void AGameModeBase::InitGame() {
       HUDClass = AKeyHUD::StaticClass();
}

Here are some things I've tried, which all don't work except to access its members which don't require internal variables. I included the most promising two. No matter what I try the statement if (defaultHUD) always returns false and if I try to access it it crashes UE4.

defaultHUD = HUDClass->GetClass();

defaultHUD = Cast<AKeyHUD>(HUDClass);

If anyone can help me out that would be greatly appreciated.

1

There are 1 answers

0
phlie On BEST ANSWER

I figured out a solution to get a reference to both any actor object and the HUD from within the Game Mode Base class, this works in Unreal Engine 4.25 using C++. After initializing the HUDClass and the DefaultPawnClass using a place that they will be initialized (I personally put them in the Game Mode Base Constructor):

HUDClass = AMyHUD::StaticClass();
DefaultPawnClass = APlayerPawn::StaticClass();

Then to get a reference to the HUD, the following code works assuming your HUD Class name is AMyHUD and is callable from many places including StartPlay():

defaultHUD = Cast<AMyHUD>(UGameplayStatics::GetPlayerController(this,0)->GetHUD());

What this does is get the HUD that is attached to the first players controller, although changing the number changes which Player Controller to get a reference from.

Now to get a reference to any actor of a class the following code works, also placeable in StartPlay():

TArray<AActor*> FoundPawns;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), APlayerPawn::StaticClass(), FoundPawns);

defaultPawn = Cast<APlayerPawn>(FoundPawns[0]);

Both the defaultPawn and the defaultHUD are then callable and useable in a straightforward manner such as:

defaultPawn->YourActorsFunction();

I hope that helps save people time and is useful.