Hello, I am trying to discover the ordering of the objects in the array returned by GameObject.FindGameObjectsWithTag().
Is the order something that I can depend on such as being based on the name of the object? Or is it some other property or defined by the initialization time of the object?
The ordering of most of unity's commands which return lists of objects is not specified (i.e. it is undocumented). This includes the arrays returned by:
For this reason, you shouldn't ever assume that objects will always occur in a certain order, or following a certain pattern from these functions, even if they seem to do so in your build. For example, an update to the webplayer could potentially change how these functions work "under the hood", resulting in a different ordering, after you deployed your webplayer!
So, the upshot is that you need to design your systems in such a way that does not rely on the ordering of these results.
If you need to collect objects in a certain order (for example a series of waypoints around a circuit in your scene), I would advise naming them numerically, and finding them by name at the start of your script, as described here.
I just did a quick test and name is definitely not the determining factor for the order.
Observationally I'd guess there's an internal array built at startup for each tag, so it is probably filled in based on the order the objects were added to the scene, then at runtime if there are any changes to tags they seem to be just added to the end of that list. That's just based on a few minutes of testing though, so don't quote me.
If you need them to be sorted by name, you can do that easily enough, e.g. (C#):
GameObject[] FindObsWithTag( string tag )
{
GameObject[] foundObs = GameObject.FindGameObjectsWithTag(tag);
Array.Sort( foundObs, CompareObNames );
return foundObs;
}
int CompareObNames( GameObject x, GameObject y )
{
return x.name.CompareTo( y.name );
}
The order is undefined, so you can't count on it in any way. Even if you find something that works now, it can change in the future, so you have to use some defined way of ordering the objects (sorting by name or whatever).