index number problems Forloop
i cant seem to get the right index number. it does set the lowest number but it always returns i = 0 in the debug log.
it must be somthing simple but i cant see it.
public void FindClosest(){
if (CurrentTargets.Count == NodeDistances.Count) {
int Lowest = 99999;
int indexNumber = 0;
for (int i = 0; i < NodeDistances.Count - 1; i++) {
if (Lowest > NodeDistances [i]) {
Lowest = NodeDistances [i];
indexNumber = i;
Debug.Log (i + "lowest Number" + Lowest );
}
}
target = CurrentTargets [indexNumber];
PathRequestManager.RequestPath (transform.position, target.position, OnPathFound);
}
}
Are you sure NodeDistance[0] isn't simply the lowest value in the array?
i have 3 other targets in the array,even if 0 = 27 units and 1 = 4 units and 2 = 6 units it still goes to [0].
I can't make this code fail!
I've tried with both an int array and changing Count to Length and then, because that worked perfectly, I switched to a List List and back to Count, it just seems to work every time. I can post the entire script if you want but it's almost identical to yours.
Answer by jgodfrey · Jun 11, 2016 at 12:16 PM
Your loop indexer is wrong and will cause the last array element to not be processed. This:
i < NodeDistances.Count - 1
Should be:
i < NodeDistances.Count
That said, I don't see how that could cause the problem you describe (based on the mentioned sample data). Nothing else jumps out at me, but it should be easy to find by adding some additional Debug.Log statements. Dump everything you're working with in the loop (current index, current value, Lowest" value, etc) and see what's not right.
it was in deed the -1. i found it after taking a break. but thanks annyway :)
Your answer
Follow this Question
Related Questions
Finding all the same strings in a List 2 Answers
I need help finding the index of an object in a list. 1 Answer
Trying to index a list, gives error. 1 Answer
Unknown Argument Out of Range Index Error On Card Game 1 Answer
[ANSWERED] IndexOf and LastIndexOf both returning -1 when an item is on the list. 1 Answer