I think the problem is:
-
HitResult, during UBT optimisation, moves out of for loop, so you pointer always point on same variable (if your traces succeed at least once). Otherwise, your pointer would always be invalid (if found result) because of for loop scope (general C++ syntaxsis). - You overwrite
HitResultevery for loop iteration, even if no hit or new hit location is not suitable (LineTrace feature). And, because of 1), your pointer’s value changes every iteration too.
I think, the possible solution is to manually allocate memory for pointer if you find a solution and after what assign a value:
if (DeepestHit == nullptr){ // we found a hit, but, in case this is a first result (DeepestHit is nullptr), allocate memory
DeepestHit = new FHitResult();
}
if (Distance < DistanceToImpactPoint) // always true on first found hit result
{
*DeepestHit = HitResult; // copy data of found result to memory address in DeepestHit
DistanceToImpactPoint = Distance;
}
... //just some your code
if (DeepestHit != nullptr)
{
DrawDebugPoint(GetWorld(), DepestImpactPoint, 5.f, FColor::Red);
UE_LOG(LogTemp, Warning, TEXT("Dist: %f"), DistanceToImpactPoint);
//do whatever you want
delete DeepestHit; // free memory to avoid memory leak (maybe not here, depends on your code, but manualy free required because it's not UPROPERTY or smart)
}
Working with raw pointers is hard (it’s a possible place of memory leaking), so try to use TSharedPtr<FHitResult> instead:
TSharedPtr<FHitResult> DeepestHit; //just make your DeepestHit as a smart pointer (nullptr is default).
... //other your code
if (Distance < DistanceToImpactPoint) // always true on first found hit result
{
DeepestHit = MakeShared<FHitResult>(HitResult); // allocate memory for shared ptr with data of result, if there is previous, it automatically free if not saved somewhere else
DistanceToImpactPoint = Distance;
}
... //do whatever you want, smart pointer will be free automatically after become inaccessible.
You can read more about smart pointers here: Unreal Smart Pointer Library | Unreal Engine 4.27 Documentation