# Why when getting the waypoints objects in script the order in the array is not the same as in the hierarchy?

At the top

public GameObject[] waypoints;


In Start

void Start()
{
waypoints = GameObject.FindGameObjectsWithTag("Waypoint");
}


In the Hierarchy i have 5 Spheres: In this order:

But when using a break point i see in the variable waypoints:

Why when getting the waypoints in the script they are not in the same order ?

• Solution : waypoints = GameObject.FindGameObjectsWithTag("Waypoint").OrderBy(go => go.name).ToArray(); – Daniel Lip Nov 19 '17 at 0:46

The scene hierarchy can be reordered by dragging things around. However the default ordering (the order in which the objects were created) still applies.

The GameObject.FindGameObjectsWithTag() method makes no claims about what order the objects should or will be returned in. Presumably the order of instantiation (or even possibly, the order in which they exist in memory, or god forbid, randomly) is the order of the array when that function returns.

Your only solution is to sort the array after you get it.

If we need to sort by name for example array of GameObject:

GameObject[] waypoints = GameObject.FindGameObjectsWithTag("Waypoint").OrderBy(go => go.name).ToArray();


The result will be: Sphere , Sphere (1) , Sphere (2)

Then if we want to reverse the array after sorted: We add the line:

Array.Reverse(waypoints);


The result: Sphere (2) , Sphere (1) , Sphere

If we have array of int or float for example:

    float[] test = new float[5];
test[0] = 1f;
test[1] = 2.5f;
test[2] = 1.1f;
test[3] = 0.5656f;
test[4] = 66f;

Array.Sort(test);
Array.Reverse(test);


As mentioned on this page the order of objects returned from FindGameObjectsWithTag is unspecified, so you can't rely on it returning objects in any specific order.

You could manually set the waypoints to the array in the inspector, or sort them by their waypoint index after getting them with FindGameObjectsWithTag.