Enum.GetNames() not working properly...

I need to construct an array with a size equal to the number of elements in an enum. The following test code works just fine:

    public enum Test
    {
        A = 0,
        B,
        C,
        D,
        E,
        F,
        G,
        H,
        I
    }

    public int testSize = Enum.GetNames(typeof(Test)).Length;
    public int [] test = new int[Enum.GetNames(typeof(Test)).Length];

In my MonoBehaviour Start() function, I can see that “testSize” evaluates to 9 and the size of the “test” array is 9. Now, if I simply add an additional element to the enum, like so:

    public enum Test
    {
        A = 0,
        B,
        C,
        D,
        E,
        F,
        G,
        H,
        I,
        J
    }

“testSize” correctly evaluates to 10 but the size of the “test” array is still 9. This happens with my actual game code and with the above test code. Am I doing something utterly diabolical? Is this a C# bug?

test is serialized by Unity - ie. read from whatever you put in there in the inspector.

When you have a serialized field declared like this:

public int [] test = something;

That means that ‘something’ will be used to fill the field if there isn’t already data there. Since you had the object open with the old values, they got written to file, and is now used.

Looks like you don’t want the test array to be serialized, so you probably want it to either be private, or marked as [NonSerialized]

1 Like

Omg, thank you. This was driving me nuts. :slight_smile: