Return related values together
The result keeps the actor and its distance together, while TOptional handles the case where no target was found.
struct FTargetSearchResult
{
AActor* Target = nullptr;
float Distance = 0.0f;
};
TOptional<FTargetSearchResult> FindClosestTarget(
const FVector& Origin,
const TArray<TObjectPtr<AActor>>& Candidates)
{
AActor* ClosestTarget = nullptr;
float ClosestDistanceSquared = TNumericLimits<float>::Max();
for (AActor* Candidate : Candidates)
{
if (!IsValid(Candidate))
{
continue;
}
const float DistanceSquared = FVector::DistSquared(
Origin,
Candidate->GetActorLocation());
if (DistanceSquared < ClosestDistanceSquared)
{
ClosestTarget = Candidate;
ClosestDistanceSquared = DistanceSquared;
}
}
if (ClosestTarget == nullptr)
{
return {};
}
return FTargetSearchResult{
ClosestTarget,
FMath::Sqrt(ClosestDistanceSquared)
};
}- Why
- The caller cannot read a distance when no target exists or forget to initialize an output variable. You can also add another result field later without changing every call site.
- Costs
- A result struct adds another type. That is unnecessary when a function returns one required scalar.
- Instead
- Use a direct value return for one mandatory result. Use output parameters when matching an established Unreal API or when each output is independently optional.

