# How to find the minimum number in a float array C#

i have a for loop that detects the position of every game object in a list and gets the difference between that object and an object anchored in the center and then stores all values in a float array. what should happen next is find the minimum distance in that array and make that object (the object with the smallest distance) move towards the anchored center. the problem is that no matter what i do, it always gets the maximum number (which is the furthest game object). here is what i have so far:

``````public RectTransform panal;
public GameObject[] characters;
public RectTransform center;

private float[] distance;
private float minDistance;
private bool isDragging = false;
private int distanceBetweenCharacters;
private int minCharNum;

private void Start()
{
int charLength = characters.Length;

center = GameObject.Find("CenterCompare").GetComponent<RectTransform>();

distanceBetweenCharacters = 200;
}

private void Update()
{

for (int i = 0; i < characters.Length; i++)
{
distance _= Mathf.Abs(characters*.transform.position.y - center.transform.position.y);*_
``````

}
float minDistance = Mathf.Min(distance);
Debug.Log(minDistance);
for (int a = 0; a < characters.Length; a++)
{
if (minDistance == distance[a])
{
minCharNum = a;
}
}
Debug.Log(minCharNum);
if (!isDragging)
{
LerpToChar(minCharNum * distanceBetweenCharacters);
}
}
void LerpToChar(int position)
{
float newY = Mathf.Lerp(panal.anchoredPosition.y, position, Time.deltaTime * 5f);
Vector2 newPosition = new Vector2(-386, newY);
panal.anchoredPosition = newPosition;
}
public void StartDrag()
{
isDragging = true;
}
public void EndDrag()
{
isDragging = false;
}
I assume that the problem is with the array because when i set the minCharNum to a specific integer, it works just fine. What am i doing wrong exactly? Any help is very much appreciated.

private void Update()
{
// needs to be max distance so can find values that are less
float minDistance = float.MaxValue;
int closestCharacter = 0;

``````    for (int i = 0; i < characters.Length; i++)
{
// get this distance
float thisDistance = Mathf.Abs(characters*.transform.position.y - center.transform.position.y);*
``````

// save distance
distance = thisDistance;

// compare and update minimum distance & closest character if required
if (thisDistance < minDistance)
{
minDistance = thisDistance;
closestCharacter = i;
}
}

if (!isDragging)
{
LerpToChar(closestCharacter * distanceBetweenCharacters);
}
}