Download

Accessing Pawn Class Public Variable C++

Hello
I have a problem with accessing the Pawn class public variable from HUD class. Code is compiling without any error , but when I press play inside the editor UE is crashing.

First-chance exception at 0x00007FF9F1FAA65B (UE4Editor-VehicleGame-Win64-DebugGame.dll) in UE4Editor.exe: 0xC0000005: Access violation reading location 0x00000000000003A8.

void AVehicleHUD:: DrawHUD()
{
Super:: DrawHUD();
AVehicle* DummyBot = Cast<AVehicle>(UGameplayStatics::GetPlayerPawn(this, 0));
FString PowerLevelString = FString::FromInt(DummyBot->PowerLevel);
DrawText(PowerLevelString, FColor::Red, 50, 50, HUDFont);
}

Maybe someone has an idea what is wrong with it. I tried to find information but without any success.

Hi,

It’s hard to say without seeing all of your code, but obious things to check is if player pawn at index 0 is indeed a AVehicle (derived from APawn), and I assume that PowerLevel is just an int32 (i.e. not a pointer).

PS! When the engine crashes you usually get a call stack dump, and if so then it’s a good idea to post the whole thing as that access violation doesn’t tell us much - except that there was an access violation :slight_smile:

I would say that in this case your variable ‘DummyBot’ is probably NULL. You need to check the result of your cast before you use the variable. So:



void AVehicleHUD:: DrawHUD()
{
   Super:: DrawHUD(); 
   AVehicle* DummyBot = Cast<AVehicle>(UGameplayStatics::GetPlayerPawn(this, 0)); 
   if (DummyBot) {
      FString PowerLevelString = FString::FromInt(DummyBot->PowerLevel);
      DrawText(PowerLevelString, FColor::Red, 50, 50, HUDFont);
   }
}


Thank You for you suggestion I solved my problem
‘DummyBot’ was null that why editor crashed.
Thank you

Hello.

You should check your pointers before accessing them.

if pointer is null, it will return false and the if statement will fall through and no exception will be thrown. Some objects might require you to check to see if they are locked by another thread before accessing them as well.

Cheers.

It seems UE4 uses check (and not just for pointers), so if you want to make it even cleaner you could simply do:


void AVehicleHUD:: DrawHUD()
{
   Super:: DrawHUD(); 
   AVehicle* DummyBot = Cast<AVehicle>(UGameplayStatics::GetPlayerPawn(this, 0)); 
   check(DummyBot);
   FString PowerLevelString = FString::FromInt(DummyBot->PowerLevel);
   DrawText(PowerLevelString, FColor::Red, 50, 50, HUDFont);
}

PS! I haven’t found the documentation or implementation for check yet, not the easiest word to search for and it’s far down my priority list.