Problem:
When a variable is referenced, UE5 will crash.
Description:
I’m trying to get a widget to display the ammo count over a gun in VR. When the weapon fires, this number will go down.
I’m working with two classes: Pistol and AmmoHUD.
Pistol is AActor and AmmoHUD is UUserWidget.
When pistol fires, it calls a function inside of AmmoHUD to decrement the ammo count.
If the text block that holds the text to display is referenced in this function it will crash the editor. Also, any variable referenced here will also crash the editor.
On begin play in the editor, the widget is displayed correctly. But as soon as I fired the pistol, the engine crashes. The error log references line #25 in AmmoHUD.cpp and line #68 in Pistol.cpp
If the conditional (line #25 AmmoHUD) is commented out, “CurrentAmmo” is logged and decremented successfully.
I’m not sure why this variable is crashing UE5 when called from the pistol. Especially when the variable is shown as existing in the previous NativeConstruct(). I’m thinking the problem may be in the way I have created the Widget Component in Pistol.cpp, or the way I am calling the function and casting in Pistol.cpp.
I’m mashing a few tutorials together, so there is probably a better way to do this, but any help would be appreciated!
Pistol.h
public:
UPROPERTY(VisibleAnywhere)
class UWidgetComponent* AmmoHUD;
void FireWeapon();
int32 AmmoCount = 10;
Pistol.cpp
APistol::APistol()
{
//...
AmmoHUD = CreateDefaultSubobject<UWidgetComponent>(TEXT("AmmoHUD"));
AmmoHUD->SetupAttachment(SkeletalMesh);
..//
void APistol::FireWeapon()
{
AmmoCount -= 1;
UAmmoHUD* HUDToFire = Cast<UAmmoHUD>(AmmoHUD);
// line #68 crash reference
HUDToFire->SetAmmoCount(AmmoCount);
}
AmmoHUD.h
class VRCONTROLLERS_API UAmmoHUD : public UUserWidget
{
GENERATED_BODY()
public:
virtual void NativeConstruct() override;
// Widget to use to display current Ammo in clip
UPROPERTY(EditAnywhere, meta = (BindWidget))
class UTextBlock* AmmoDisplayNew;
// Update the HUD with current Ammo count in clip
void SetAmmoCount(int32 CurrentAmmo);
};
AmmoHUD.cpp
void UAmmoHUD::NativeConstruct()
{
Super::NativeConstruct();
UE_LOG(LogTemp, Warning, TEXT("Native Construct")); // this always fires
if(AmmoDisplayNew) {
UE_LOG(LogTemp, Warning, TEXT("has ammoDisplay")); // this always fires
}
}
void UAmmoHUD::SetAmmoCount(int32 CurrentAmmo)
{
UE_LOG(LogTemp, Warning, TEXT("The integer value is: %d"), CurrentAmmo); // this will fire and decrement correctly if the below "if" statement is commented out
// line #25 crash reference
if(AmmoDisplayNew) // this will crash when called, even though variable is working above in NativeConstruct()
{
UE_LOG(LogTemp, Warning, TEXT("set count firing"));
}
}