Unity crashes when initializes an EnumField with a dynamic generated Enum

Greetings. I’m using dynamic generated enums to laverage the EnumField with the following code

  private Enum GenerateTempEnum(string[] fields, string name)
    {
        if (fields.Length == 0)
        {
            return null;
        }

        AssemblyName aName = new AssemblyName("TempEnumAssembly");
        AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.ReflectionOnly);
        ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

        EnumBuilder eb = mb.DefineEnum(name, TypeAttributes.Public, typeof(int));

        for (int i = 0; i < fields.Length; i++)
        {
            string f = fields[i];
            eb.DefineLiteral(f, i);
        }

        Type enumType = eb.CreateType();
        Enum tempEnum = (Enum)Enum.ToObject(enumType, 0);
        return tempEnum;
    }

The enum is generated correctly but when I initialize the EnumField Unity crashes completely

 Enum tempEnum = GenerateTempEnum(_propertiesNames, "EnumProperties");
_myEnumField.Init(tempEnum);

This used to work in 2019.1. Now I’m using 2019.3.0f3

I ended up creating my own version of EnumField. It works like a charm

Hi jmprocco,

I did a little investigation and Unity is caching Enum data for performance reasons.
However, this optimization doesn’t seem to work well with generated enums.

The crash happen on this line here : UnityCsReference/Editor/Mono/EnumDataUtility.cs at master · Unity-Technologies/UnityCsReference · GitHub

I tried to work around this but ran onto other issues later on.
My personal recommendation is to not use generated enums to begin with.

If not possible you have a your own EnumField that you can use!

1 Like