My challenge solution (no need to call getActor() unless hit was performed

Came up with this while working on the challenge:

FHitResult Hit;
bool GotHit = GetWorld()->LineTraceSingleByObjectType(
    OUT Hit,
    PlayerViewPointLocation,
    LineTraceEnd,
    FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),
    TraceParameters
);

// See what we hit
if (GotHit) {
    FString ActorName = Hit.GetActor()->GetName();
    UE_LOG(LogTemp, Warning, TEXT("Actor Hit: %s"), *ActorName);
}

Because LineTraceSingleByObjectType() returns boolean when hit was performed, and we only need to grab actor and it’s name when the actual hit happened, I feel that this is slightly more efficient solution. THoughts?

I got nearly the same as you, except I skipped storing the result of LineTraceSingleByObjectType()…since it is a Bool , just tested it directly in the If, and as well directly referenced the Actor name instead of storing the pointer first.
I think your way is cleaner to read though! (and also Ben’s)

FHitResult Hit;   //store a hit
	
if (GetWorld()->LineTraceSingleByObjectType(
	OUT Hit,
	PlayerViewPointLocation,
	LineTraceEnd,
	FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),   // Hit masking only return physics body's
	TraceParameters)
	)
	{				// If we Hit a Physics Body then log name of the actor we hit
		UE_LOG(LogTemp, Warning, TEXT("Grabber Hit: %s"), *Hit.GetActor()->GetName());
	}

Yeah, once I realized it returned a bool, I just put it directly in an if condition with the rest of the code inside true branch.

Privacy & Terms