How GameObject.FindObjectsWithTag() order the elements?

Hello friends!

As the title says, Image we have some objects Tagged “Parent”, and all this parents have a child object Tagged “Child” . Then, when using something like this:

foreach (GameObject ParentFound in GameObject.FiondObjectsWithTag("Parent"))
Bla bla bla

How Unity choose the elemets? If you do this twice in different sesions, all the elemets will be in same order?

Then if use

foreach (GameObject ChildFound in GameObject.FiondObjectsWithTag("Child"))
Bla bla bla

Will be the childs the same order as the parents? I mean, the 3rd GameObject found in first foreach will be the parent of 3rd Gameonbject found in second foreach?

Thanks in advace!!

Bye! :smiley:

Since Unity did not document the exact behaviour you can’t rely on any, even if through testing you can identify a pattern. Anything not documented or explicitly mentioned could be changed at any time.

Just based on some analysis and common sense I would say the order is just the order in which the objects got added to the tag list. We don’t know how Unity internally handles and manages the tags. Though since it’s commonly known that FindWithTag is faster than find an object by name we can assume that Unity probably has a seperate list for each tag. When a gameobject gets a certain tag assigned Unity probably just adds this gameobject to the list for this tag. It’s unlikely that this list is sorted in any way since this would impact the performance heavily for changing the tag of a gameobject.

Since Unity doesn’t need random access to gameobjects in a tag list it may be implemented as a (doubly) linked list as this would make adding and removing an object an O(1) operation.

So the order of objects loaded from a scene probably directly depends on the order the objects are loaded. So it’s probably the order in the hierarchy / file.

I would strongly recommend to not rely on any particular order and just assume a random order. If you need some kind of order use different information.