One of the advantages of the List class is that it comes with a handful of functions out of the box in order to make our life easier when working with variable-size arrays. Among those functions is Sort, which helps us arrange the list’s elements in a given order; usually in an incremental way.

For example, declaring a list of integers, adding some values, and calling the function, work as expected:

However, things get a little dizzy when calling that function when ¬†we’re dealing with a list of vectors because, oddly, both Vector2 and Vector3 classes don’t have a function to compare two objects and determine whether the first one is greater than, less than or equals to the latter. Let’s try the following:

The previous code shows the following error:

That means Vector2, and neither does Vector3, implement the CompareTo function from the IComparable interface.

Luckily, the function is robust enough to accept a parameter for defining our own custom comparing object or function, in order to solve the aforementioned issue. Let’s see how it is done.

First, we need to create a class implementing the interface IComparer and define the function Compare. Let’s start by creating the class for comparing Vector2 objects:

As you may already know, comparing two float values using the == operator is not suitable for some situations. In order to approach that problem we can make use of the Approximately function from the Mathf class. Thus, checking whether two values are equal means checking if their approximately the same. Below, the new member function for those situations:

Then, the Sort function is implemented passing a new Vector2Comparer object as parameter

Now, it’s time to code an example class in order to test our custom function:

Finally, extending the previous example to sort a list of three-dimensional vectors (Vector3) is just a piece of cake with the new learned technique.


About Author

Programmer with 5-year experience, two of them dedicated entirely to game development. Specializing in AI and gameplay programming.

Leave A Reply