Minimum of multiple values

New day, new question…

How can I find the smallest of multiple variables, without resorting to writing a BubbleSort (or similar) algorithm myself? I would need it for Pathfinding (find the shortest path to a given point while being constrained to just move in distinct directions), so it should be as fast s possible.

I found Mathf.Min in the script reference, but I do not need the value itself, but the variable that this value is assigned to. Would I need to compare each variable to that value, or is there a better way of doing this?

1 Answer

1

If your ‘variable’ is an array or list or other container-of-many-things, then you iterate through that list and find the index of the smallest value.

Ex: (untested)

var a = new Array [3,5,7,1,3];
var lowestIndex = -1;
var minval = 1000000; // beyond expected max value
for (i=0; i < a.Length; i++)
  if (a *< minval)*

{
minval = a*;*
lowestIndex = i;
}
// at this point, lowestIndex should = 3
thus the variable you were looking for is a[lowestIndex]

Thank you. It definitely looks like it should work. I'll try and implement it and get back.

Jupp. I can confirm it does work. Many thanks for the help.