Pages

Tuesday, September 4, 2012

Unity3D + C#: Min, Max, and Sort

Min(): To find the minimum value inside an array.
Max(): To find the maximum value inside an array.

There's two kinds of commonly used array type in Unity:
- classic array, e.g.: int[], float[]
- List array, e.g.: List, List


To find the minimum value from a classic array, simply use Mathf.Min():

int[] integers = new int[4]{ 2, 4, 5, 3 };
int minValue = Mathf.Min(integers);
// return "2"
Debug.Log(minValue);

To find the maximum value, simply change the Min function to Max (or change the variable name if you want):

int maxValue = Mathf.Max(integers);
// return "5"
Debug.Log(maxValue);

To find the minimum value from a List array, however, it would not work with Mathf.Min(). If you try to put a List array into the function, it would give an error stating that Mathf.Min() only accept classic array as argument.
http://docs.unity3d.com/Documentation/ScriptReference/Mathf.Min.html

To solve the problem, you need to use an extension method from Linq.
To use Linq, first, add the following line at the top (below the "using UnityEngine;" line):

using System.Linq;

Then go back to creating a new List array, and store a couple of numbers of different value. 
NOTE: To create a List array, the line "using System.Collections.Generic;" have to be added to the top.

List integersList = new List(){ 2, 4, 5, 3 }
int minListValue = integersList.Min();
// return "2"
Debug.Log(minListValue);

Notice a ".Min()" function is added behind the List array "integerList"? (it would appear in Mono's suggestion box as soon as you've added Linq).

Same goes for finding the mac value in List array, replace the Min() function with Max().

int maxListValue = integersList.Max();
// return "5"
Debug.Log(maxListValue);

---

Sort(): To sort an array from the lowest value to the highest.

Also another method to find the min and max value from an array.
However, the Sort function only exist for List array's use, and it doesn't require Linq reference as well.

integersList.Sort();
Debug.Log(integersList[0]); // return "2"
Debug.Log(integersList[1]); // return "3"
Debug.Log(integersList[2]); // return "4"
Debug.Log(integersList[3]); // return "5"

To use Sort for classic array, simply use:

System.Array.Sort(integers);
Debug.Log(integers[0]); // return "2"
Debug.Log(integers[1]); // return "3"
Debug.Log(integers[2]); // return "4"
Debug.Log(integers[3]); // return "5"

Here's a sample script you can refer to, in case you run into any problem:
https://dl.dropbox.com/u/40305586/Test%20Scripts/Test_1.cs

No comments: