- Home /
How would you sort gameobjects by their position in a 3D grid?
Say I have a bunch of block gameobjects in a 3d grid space like in the picture below,
and they are stored as an array of gameobjects. My goal is to figure out a (hopefully simple) way of sorting them by their position in 3d space within the array such that the right-upper-top most is the first on the list and the left-lower-bottom most is the last in the array. It's kinda hard to explain but hopefully the image below shows the idea of how the blocks would be ordered in the array.
I can't just manually assign them the order in the beginning since the blocks can change their positions at runtime. Any ideas on how I would sort them in such an order would be highly appreciated.
Answer by Hellium · May 19, 2019 at 08:27 AM
The description of the "sort algorithm" you gave is different from the order you showed in the image (supposing on the image that the +Z axis is pointing up, and the +X axis is pointing right)
The following functions are meant to be used in the Array.Sort or List.Sort methods:
System.Array.Sort( blocks, CompareBlocks ); // if blocks in a Vector3[]
// OR
blocks.Sort( CompareBlocks ); // if blocks in a List<Vector3>
Comparison function according to the image
public static int CompareBlocks( Vector3 v1, Vector3 v2 )
{
// Comparing two vectors this way is fine
// Unity has overloaded the == operator
// So as to avoid floating point imprecision
if ( v1 == v2 ) return 0;
if ( Mathf.Approximately( v1.x, v2.x ) )
{
if ( Mathf.Approximately( v1.z, v2.z ) )
return v1.y > v2.y ? -1 : 1;
else
return v1.z > v2.z ? -1 : 1;
}
return v1.x > v2.x ? -1 : 1;
}
Comparison function according to the description
public static int CompareBlocks( Vector3 v1, Vector3 v2 )
{
// Comparing two vectors this way is fine
// Unity has overloaded the == operator
// So as to avoid floating point imprecision
if ( v1 == v2 ) return 0;
if ( Mathf.Approximately( v1.z, v2.z ) )
{
if ( Mathf.Approximately( v1.x, v2.x ) )
return v1.y > v2.y ? -1 : 1;
else
return v1.x > v2.x ? -1 : 1;
}
return v1.z > v2.z ? -1 : 1;
}
Yeah I probably could've worded the description a lot more carefully but your comparison function according to the image worked perfectly! Only change I needed as to convert the Vectors to GameObject positions so that it works with the GameObject array. Thanks a ton! Hopefully someone else will find the other comparison function helpful.