I’m currently trying to display the players health using UE 4.9 into my HUD class. (referencing through this tutorial - YouTube)
I’m having trouble passing in data into my HUD class. My _health variable is private, so i created a get method for another class to access its value. Even though the code compiles it seems like no data is being passed in, and im not sure why. I tried to print out the health value into my console through this function in my character source code but it seems like this method is never called at all.
Any help would be greatly appreciated.
TestFPSCharacter.cpp
/**
* _health is private and set to 50.f; in the constructor, so return its value through a public get method
*/
float TestFPSCharacter::GetHealth()
{
FString _tmp = FString::SanitizeFloat(_health);
GEngine -> AddOnScreenDebugMessage(-1, 2.f, FColor::Red, TEXT("health is : ") + _tmp);
return _health;
}
My HUD header file:
#pragma once
#include "GameFramework/HUD.h"
#include "CharacterHUD.generated.h"
/**
*
*/
UCLASS()
class EPSILONFPS_API ACharacterHUD : public AHUD
{
GENERATED_BODY()
public:
ACharacterHUD();
UPROPERTY()
UFont* _HUDFont;
virtual void DrawHUD() override;
private:
UTexture2D* _crosshairTex;
void PlayerHealth();
};
My HUD implementation file:
#include "EpsilonFPS.h"
#include "CharacterHUD.h"
#include "Engine/Canvas.h"
#include "Engine/Font.h"
#include "TestFPSCharacter.h"
#include "Engine.h"
#include "kismet/GameplayStatics.h"
/**
* constructor
*/
ACharacterHUD::ACharacterHUD()
{
static ConstructorHelpers::FObjectFinder<UTexture2D> CrosshairTexObj(TEXT("Texture2D'/Game/crosshair.crosshair'"));
static ConstructorHelpers::FObjectFinder<UFont> HUDFontOb(TEXT("/Engine/EngineFonts/RobotoDistanceField"));
_crosshairTex = CrosshairTexObj.Object;
_HUDFont = HUDFontOb.Object;
}
/**
* Draw the HUD by overriding DrawHUD
*/
void ACharacterHUD::DrawHUD()
{
Super::DrawHUD();
ACharacterHUD::PlayerHealth();
const FVector2D Center( Canvas -> ClipX * 0.5f, Canvas -> ClipY * 0.5f);
const FVector2D CrosshairDrawPosition((Center.X - (_crosshairTex->GetSurfaceWidth() * 0.5)), (Center.Y - (_crosshairTex->GetSurfaceHeight() * 0.5f)));
FCanvasTileItem TileItem(CrosshairDrawPosition, _crosshairTex -> Resource, FLinearColor::White);
TileItem.BlendMode = SE_BLEND_Translucent;
Canvas -> DrawItem(TileItem);
}
/**
* Get players health to display in the HUD
*/
void ACharacterHUD::PlayerHealth()
{
// Get the players health
ATestFPSCharacter* _myCharacter = Cast<TestFPSCharacter>(UGameplayStatics::GetPlayerPawn(this, 0));
FString _healthString = FString::Printf(TEXT("%10.0f"), FMath::Abs(_myCharacter -> GetHealth()));
DrawText(_healthString, FColor::White, 50, 50, _HUDFont);
}
Thanks!