Target distance would only update closer

Hey so i have this script where i get the current target distance and it works fine when the target moves closer to the object but if the target moves further away it dosnt update the distance can somebody help me

public void TargetFinder()
    {
        foreach (var x in enemies)
        {
            float distance = (transform.position - x.transform.position).magnitude;

            if (distance < currentTargetDistance)
            {
                myTarget = x;
                displayText.text = "My target: " + x + "

Distance to Target: " + distance; //skal fjernes nå det er helt klart
currentTargetDistance = distance;
}
}
}

Sure it doesn’t update. You “distance” variable is the distance in this frame and “currentTargetDistance” is distance in previous frame. When moving away, “current…” will never be smaller than “distance”.

I assume you want to find distance to the closest enemy? After the foreach, calculate distance to your current target and assign it to “currentTargetDistance”

Also this line

float distance = (transform.position - x.transform.position).magnitude;

can be switched to

float distance = Vector3.Distance(transform.position, x.transform.position)