# Convert variables to array, then find the max value.

Hi everyone.

As the title suggests, I’m looking for a way to get the values of some variables into an array, then find which variable has the highest value. Using the example given here (Find Highest Value in Array - Questions & Answers - Unity Discussions), I was hoping to do something like the following :

``````var action1;
var action2;
var action3;
var action4;
var action5;

function Start () {
action1 = 100;
action2 = 50;
action3 = 40;
action4 = 20;
action5 = 10;

var foo = [action1, action2, action3, action4, action5];

Debug.Log (MaxValue(foo));
}

function MaxValue (intArray : int[]) : int {
var max = intArray[0];
for (i = 1; i < intArray.Length; i++) {
if (intArray[i] > max) {
max = intArray[i];
}
}
return max;
}
``````

Though I know this doesn’t work. Is something like this possible, and if so, how would I do it?

If there’s a way to do this which doesn’t include an array, it’s also something I’d like to hear about.

Either way (with an array or not), you need to compare all the values to find the highest one…
If you google this, you will find a bunch of potential solutions.
Your logic here, works. I don’t have time to test it out, but logically it works.
If it doesn’t: check if you have errors.

And quite more simply, you can use Mathf.Max(), like this (code is in C#)

``````int[] tempArray ={0, 1, 4, 23, 6, 5};
Debug.Log("MAX ELEMENT OF THE ARRAY! "  + Mathf.Max(tempArray)); //Will output 23!
``````

For floats values, change int[ ] to float[ ], and make sure to add f to all numbers that have decimal values. For good practice add f to all of them…

``````float[] tempArray ={0f, 1f, 4f, 23f, 6f, 5f, 23.1f};
Debug.Log("MAX ELEMENT OF THE ARRAY! "  + Mathf.Max(tempArray)); //Will output 23.1!
``````

If it helps, the error I get when I try to run the code is “InvalidCastException: Cannot cast from source type to destination type.”.