1
\$\begingroup\$

At the top

public GameObject[] waypoints;

In Start

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

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

waypoints

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

waypoints

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

\$\endgroup\$
1
  • \$\begingroup\$ Solution : waypoints = GameObject.FindGameObjectsWithTag("Waypoint").OrderBy(go => go.name).ToArray(); \$\endgroup\$
    – Daniel Lip
    Nov 19, 2017 at 0:46

3 Answers 3

7
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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);
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .