- Home /
Cube Sorter
Ok so in my scene, I have an empty game object called CubeMaster.
Inside are 5 cubes. Each cube is in a line, but their order on scale is mixed up.
My goal is to sort them all with a click of a button.
I am using the BubbleSort algorithim for this task.
I made a script called SortObjects. This is what it looks like:
public class SortObjects : MonoBehaviour
{
public GameObject cubeParent;
private GameObject[] CubesToSort;
public void onClick()
{
CubesToSort = new GameObject[cubeParent.transform.childCount];
for (int i = 0; i < cubeParent.transform.childCount; i++)
{
CubesToSort[i] = cubeParent.transform.GetChild(i).gameObject;
}
BubbleSort(CubesToSort);
}
private void BubbleSort(GameObject[] A)
{
int i;
int j;
Vector3 temp;
for (i = (A.Length - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if((A[j - 1].transform.localScale.sqrMagnitude) > (A[j].transform.localScale.sqrMagnitude))
{
temp = A[j - 1].transform.position;
A[j - 1].transform.position = A[j].transform.position;
A[j].transform.position = temp;
} // end if
} // end for 2
} //end for 1
}
}
Basically what it does is checks if the cube to its right is bigger, then they are flipped around. This process is repeated until they are sorted. Unfortunately when I press my button, it looks like this:
Before:
After:
Did I do something wrong?
supportpic1.png
(88.0 kB)
supportpic2.png
(89.1 kB)
Comment