Why is this not working?

So, I am having a very strange problem,
All I am trying to do is find the closest overlapped weapon actor to the player and display it’s UI but it’s not working
here is the code:

	TArray overlaps;
	GetCapsuleComponent()->GetOverlappingActors(overlaps);
	float closestDist = INFINITY;

	for (int i = 0; i < overlaps.Num(); i++) 
	{
                 //My weapon class
		AWeaponActor* castActor = Cast(overlaps[i]);
		if (castActor)
		{
			float dist = this->GetDistanceTo(castActor);
			closestDist = FMath::Min(dist, closestDist);
			if (dist == closestDist)
			{
                                //storing the weapon actor
				CurrentStoredMeshData = castActor;
				castActor->_WeaponUI->SetVisibility(ESlateVisibility::Visible);
			}
			else 
			{
				castActor->_WeaponUI->SetVisibility(ESlateVisibility::Hidden);
			}
                       /* I also tried this but it does not work:
			if (dist < closestDist)
			{
                                closestDist = dist;
                                //storing the weapon actor
				CurrentStoredMeshData = castActor;
				castActor->_WeaponUI->SetVisibility(ESlateVisibility::Visible);
			}
			else 
			{
				castActor->_WeaponUI->SetVisibility(ESlateVisibility::Hidden);
			}

                       */
		}
	}

Here is what happens when I try it out in the editor PIE:
(both the UI widgets should not be visible, only the closest one should be visible)

333098-prob.png


Did I do this properly? Is there any other or better way I should do it?

ok, I figured it out!


just adding a simple break statement WORKED!


here’s my new code:

	TArray overlaps;
	GetCapsuleComponent()->GetOverlappingActors(overlaps);
	float closestDist = INFINITY;

	for (int i = 0; i < overlaps.Num(); i++) 
	{
		AWeaponActor* castActor = Cast(overlaps[i]);
		if (castActor)
		{
			float dist = this->GetDistanceTo(castActor);
			closestDist = FMath::Min(dist, closestDist);
			if (dist == closestDist)
			{
				CurrentStoredMeshData = castActor;
				castActor->_WeaponUI->SetVisibility(ESlateVisibility::Visible);
				break;
			}
			else 
			{
				castActor->_WeaponUI->SetVisibility(ESlateVisibility::Hidden);
			}

		}
	}