FHitResult variable sometimes throws an error

Sometimes it works fine, but sometimes it throws “__imp_FActorInstanceHandle::FetchActor(…) returned nullptr”. This is a bullet actor, so there are lots of instances in the scene, is this possible that they interfere each other somehow?

if (GetWorld()->LineTraceSingleByObjectType(HitOut, PreviousLocation, GetActorLocation(), ObjectsToDamage, QueryParams)) {
		if (HitOut.GetActor()->CanBeDamaged()) {  //VS shows that the error is here
			UE_LOG(LogTemp, Warning, TEXT("Can be Damaged"));
		}
		else {
			UE_LOG(LogTemp, Warning, TEXT("Can't be Damaged"));
		}
		GetWorld()->DestroyActor(this);
	}

There’s no garauntee that the hit result contains a valid actor. The code should look like the following:

const AActor* HitActor = HitOut.GetActor();
if (IsValid(HitActor) && HitActor->CanBeDamaged())
{

}
else
{

}

FHitResults’ ‘Actor’ member is a Weak Pointer, so the IsValid() call is not strictly required (you should at least check against nullptr though), but you should use IsValid() for checking UObject pointers anyway, to avoid messing with objects that are pending garbage collection.

2 Likes