- Home /
How to find the index of the min value in a list
Hey guys, I have a list of distances between an enemy unit and player units. I want to find the index of the min value so I can have my enemy go towards that unit. I have looked through google and there seems to be a C# function for min but it isnt working for me. Maybe the libraries are different? From what I read the code would look like this:
float minListIndex = distanceList.IndexOf(distanceList.Min());
But unity doesnt recognize the ".Min()"
Answer by Cherno · May 26, 2014 at 09:30 PM
You could try to sort the List first using Linq so the elements are arranged from lowest to highest, and then just get index 0.
Here's related thread where I asked about Array sorting, this will get you started if you want to go that route. It's actually pretty easy.
http://answers.unity3d.com/questions/548366/sorting-an-array-of-gameobjects-by-values-inside-t.html
You can also iterate through all elements in the list like this:
float minDistance;
for(int i = 0; i < myList.Count - 1; i ++) {
if(i == 0) {
minDistance = myList[i];
}
if(myList[i] < minDistance ) {
minDistance = myList[i];
}
}
@Cherno Looking at your code above, it sets the $$anonymous$$ distance as the first number it iterates through, then compares the rest of the values in the list to this $$anonymous$$ number. I dont think this would work because the first number isnt necessarily the $$anonymous$$ number, and also if I wanted to get the index, it would give the index of the sorted list (assu$$anonymous$$g this is sorted) not the index of my current list.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
RTS units team 2 Answers
Find specific element when duplicates exist in list. 1 Answer
Vector3(x,y,variable)? 0 Answers
Insert a string to a list inside a list 3 Answers