Download

how do i prevent engine from crashing?

hey guys i have got a problem in logging out the name of things that I hit if I hit something its okay but if I don’t and still try to log out the name of the actor that was hit it will result in a crash how do I fix it?

void AMain::InterAct()
{
if (OwnerPawn)
{
AController* OwnerContrller = OwnerPawn->GetController();

if (OwnerContrller)
{
FVector Location;
FRotator Rotation;

OwnerContrller->GetPlayerViewPoint(Location, Rotation);

FVector End = Location + Rotation.Vector() * CastingRange;

FHitResult Hit;
FCollisionQueryParams Params;
Params.AddIgnoredActor(this);

GetWorld()->LineTraceSingleByChannel(Hit, Location, End, ECollisionChannel::ECC_Visibility, Params);

DrawDebugLine(GetWorld(), Location, End, FColor::Red, false, 5.f);

FString HitName = Hit.GetActor()->GetName();

UE_LOG(LogTemp, Warning, TEXT(“The component name %s”), *HitName);
}
}
}

@bumbumgoesnuts you could use Assert **ensure **before accessing something NULL for more context ( you can write messages ), or you could just check if it is NULL:



if (HitName)
{
UE_LOG(LogTemp, Warning, TEXT("The component name %s"), *HitName);
}

Assert:

i know how the if statements work. u cant just put a string variable in the expression it needs a boolean which I don’t know how to get from a string literal

This is very easy, just check if you hit something.
Replace



FString HitName = Hit.GetActor()->GetName();


with



if(Hit.bBlockingHit){
FStrint HitName = Hit.GetActor()->GetName();
UE_LOG(LogTemp, Warning, TEXT("The component name %s"), *HitName);
}


or



if(Hit.GetActor()){
FString HitName = Hit.GetActor()->GetName();
UE_LOG(LogTemp, Warning, TEXT("The component name %s"), *HitName);
}


Your game crashes because the value GetActor() returns is NULL (when you don’t hit anything). When a reference is NULL, it points to the location 0x00000000, and you do not have acces to that location in memory. Keep in mind, always check if a refference is valid before using it (for this you just use a regular “if” statement).

You can use



*GetNameSafe(TheActor)


Which will safely handle null objects and convert the result to TCHAR for printing to the log.