How does Unity sort fields in order of their declaration?

If you have

public class Test : MonoBehaviour
{
    public int x, y;
    public Transform t;
    public GameObject go;
}

In the inspector, you’ll see these fields in this exact order! My question is how?

doing a: typeof(Test).GetMembers() isn’t guaranteed to return members the order they’re declared in (src)

My stab is that they either use MonoCecil somehow to get them in that order, or convert the class code to string, parse the code, use regex to get the fields’ names and then do type.GetField(name)

Edit: So in case of fields it seems that GetMembers or GetFields do indeed return the members/fields in the correct order. However; changing one of the fields to be a property will yield different results, i.e. a Transform t { get; set; } instead of
Transform t;

I asked in MonoCecil’s google group here if it could help or not, seems the only is via parsing the source code.

Well, to answer that question: we simply don’t know as there is no way in pure C# / reflection to determine the order since it is irrelevant and the compiler might even change the order when compiling.

I have some counter questions:

  • Why is it important? :slight_smile:
  • Have you tried GetMembers? The docs just state that you can’t rely on a certain order since that’s not specified in specification. However if the compiler outputs the members in the declaration order it’s most likely that GetMembers will return the members in that order.

It is known that Unity uses the Cecil library a lot. But i don’t think that they try to keep the declaration order “by any means necessary” since it doesn’t really matter in most cases. Serialization happens based on the fields name.