- Home /
How to Sort Multiple Vector Arrays in order of Values
My goal was to find a way to sort a Vector3 based on the value of X, then the value of Y, and then Z. Therefore if value1.x is less than value2.x check the y values.
The application for this code was to keep track of the current place (1st, 2nd, etc.) of race cars on a track using 3 variables: Laps, Specific Points, and Distance to the next Point. If you are a Lap ahead then it would ignore the next point and distance to that point.
After hours of exhaustive research I found the code I needed that I adapted to sort multiple vectors. I decided to post it here because I could not find this specific information anywhere, related to sorting Vector2's, 3's, etc.
Answer by Howey-Do-It · May 02, 2013 at 11:14 AM
using System;
public class SortingVectors : MonoBehaviour {
public Vector3[] playerInfo;
void Start ()
{
playerInfo = new Vector3[8];
}
void Update ()
{
Array.Sort(playerInfo, Vector3Compare);
}
private int Vector3Compare(Vector3 value1, Vector3 value2)
{
if (value1.x < value2.x)
{
return -1;
}
else if(value1.x == value2.x)
{
if(value1.y < value2.y)
{
return -1;
}
else if(value1.y == value2.y)
{
if(value1.z < value2.z)
{
return -1;
}
else if(value1.z == value2.z)
{
return 0;
}
else
{
return 1;
}
}
else
{
return 1;
}
}
else
{
return 1;
}
}
}
This arranges the Vector3's based on the X value first, Y second, and then Z.
While this may be very straightforward to many of you, it wasn't until I wrote this out that I fully understood what declaring an int/function actually allows you to do (I probably still don't fully understand).
I hope this helps someone and I believe people will find other applications for this, even with Vector2's or Vector4's.
Thanks for being awesome!
God bless!
Howey
Your answer
Follow this Question
Related Questions
How to sort a list of gameobjects by their name? 4 Answers
List.Sort with IComparer 2 Answers
How to arrange list 3 Answers
A node in a childnode? 1 Answer
Change index values in list 0 Answers