Search Unity

How to make a custom enumeration for Unity? -> full guide + code

Discussion in 'Scripting' started by orionsyndrome, Sep 16, 2022.

  1. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    Introduction
    First of all, this is one of those things where people just can't agree with each other. Should you use enum, or should you build an OOP system surrounding your types, or maybe it's ScriptableObject that is used both as the thing that goes into the thing, and the wrapper thing held above the another ScriptableObject which enumerates mini ScriptableObjects.... meh, you get the point. We can always weigh pros and cons of each approach and certainly there are numerous benefits to be had from a robust design solution, but I won't go further into this discussion.

    Let's just assume there are legit reasons why someone would really want to use an enum inside their project, and not just use them as tiny human-readable tokens for some system settings within the code, never to be seen again, but throughout the game logic as well, sprinkled in critical places, as contextual lightweight atomic data.

    "Okay so let's just use enum" Uhuh, well, you see, there's a problem with how C# enums work and how Unity treats them. THEY ARE TERRIBLE for any kind of iterative design: you set them up, you give them names, you give them values, you're better not to touch them ever again, especially in a collaborative environment. If you don't give them explicit values, then you must not reorder them as well. In my early days, I remember having just a few enum classes to describe my monster categories and certain damage types. By the end of that project these couple of classes had more commentary in them (DON'T MOVE THIS, DON'T TOUCH THAT) then any other meaningful C#.

    The other, HUGE problem with enums in Unity is that they serialize as their values. Now imagine if you had four monsters: Duck, Beaver, Rabbit, and Possum. What should their values be? It doesn't matter right?

    So you'd write it as such
    Code (csharp):
    1. public enum TerribleMonsters {
    2.   Duck,
    3.   Beaver,
    4.   Rabbit,
    5.   Possum
    6. }
    But then you choose a monster from a drop-down in some inspector field, maybe you'd like some behavior to associate with Possum, for example. And this is what saves to YAML
    Code (csharp):
    1. _selectedMonster: 3
    Does this mean anything to you? It's supposed to mean something to you, if you ever need to repair (or merge) your files. Also, what do you imagine will happen to your project if you suddenly remove the Beaver because it, idk, doesn't fit the theme or whatever, or if you add a Porcupine somewhere in between? Enums are just bad for health.

    So the main goals of this exercise will be to properly serialize our data to concrete strings, as well as to provide the expected enum behavior, in code, as well as in Unity inspectors.

    This is the approach: we'll make a so-called custom enumeration class. It kind of behaves like a standard enum, but you now have to fully specify the behavior on your end, because (sadly) there is nothing else in C# to lean onto. This means we'll have to be very creative (aka prescient) with how this is going to be used in code, but we'll also have to create a custom property drawer to present the data in a friendly manner (i.e. keep the dropdown).

    You can find more about this pattern all over the internet, even the official dot net documentation mentions it. However, I haven't seen one for Unity because it's quirky and difficult to get right.

    Tutorial begins
    That said, this is going to be an intermediate-to-heavy tutorial. It features reflection, generic programming, attributes, some newer C# syntax, and I can't possibly explain every little detail to a rookie. If you're more advanced than that (like me or better), maybe you'll learn a thing or two, and if you're an expert versed with editor-juggling and C# mastery I fully expect you to correct me if there is something you would do better.

    First things first. Standard C# enum construct exists because it lets you enumerate the names quickly and conveniently without having to write too much boilerplate surrounding the basic logic of it. We can't implement it as neatly (because we can't redefine the language syntax), so some boilerplate is necessary, but the goal is to keep it at the minimum. For the identifiers themselves we want to have a readable listing of some kind, but you can't just type words in C# and pretend it'll be alright, so it must be something like
    const
    or a regular class field to declare these values properly.

    We're gonna use
    static public readonly
    fields because enum values already behave in a static read-only fashion (edit: for the remainder of this article, don't mind me sticking static in front of public, that's just my personal convention). Consts are compile-time things which are handled differently, so it's better to keep it straight from the start. The aim is to create an abstract superclass that encapsulates the underlying logic, and then the user can derive from it, add his own fields, and call it a day.

    So something like this at a minimum?
    Code (csharp):
    1. public class MyEnum : QuasiEnum {
    2.   static public readonly MyEnum duck = new MyEnum("Duck", 0);
    3.   static public readonly MyEnum beaver = new MyEnum("Beaver", 1);
    4.   static public readonly MyEnum rabbit = new MyEnum("Rabbit", 2);
    5. }
    "But we still have to keep track of the values? And we also have to type in the names?"

    We don't actually (edit: the final product is even leaner than this). But you do want the inspector values to line up? And surely you need some values to correlate natively with the elements, it's easy to ignore them if you don't. I think this is the bare bone minimum for something that pretends to resemble an enum. The boilerplate is just unavoidable. You can still very compactly access the fields from the outside, i.e.
    MyEnum.duck
    and the identities are clearly defined and lined-up nicely.

    We should also take care of situations where we compare
    MyEnum.duck == MyEnum.beaver
    and also provide implicit conversions to value and/or string for debugging at least, and let's not forget about serialization.

    QuasiEnum
    Lets address these things by writing the core QuasiEnum class. We want each enum value to be comparable and equatable so that the rest of the system can understand how to match and compare objects of our type.
    Code (csharp):
    1. using System;
    2. public abstract class QuasiEnum : IComparable<QuasiEnum>, IEquatable<QuasiEnum> {
    3.  
    4.   public string Name { get; private set; }
    5.   public int   Value { get; private set; }
    6.  
    7. }
    Allowing protected setters is not required (and is probably not a good idea), but we can polish this some other time. Let's do the internal constructor next.
    Code (csharp):
    1. protected QuasiEnum(string name, int value) {
    2.   if(name is null) throw new ArgumentNullException(nameof(name));
    3.   if(value < 0) throw new ArgumentException("Value must be >= 0", nameof(value));
    4.   Name = name;
    5.   Value = value;
    6. }
    Notice the constrained value. We want the negative values to be signals for an improper deserialization, and especially later when we get to the property drawer. There are other, more flexible ways to do this, but who cares about values that much? In this design, the name is the king. The name is front and center, we'll use the corresponding values only as a convenience, if we do need them, or literally just to be able to sort the list in value order. But negative values? Meh.

    This also means the values can repeat, for example. That's fine, two enum entries can legally have the same value. But in our scenario two names can repeat as well, and that's illegal. But remember that we're tying these identities to field names in C# and you can't have more two fields with the same name, so we're fine there.

    "Ok, what's next. Should we implement the interfaces?" Yes, let's start with
    IEquatable
    .
    Obviously with IEquatable you also want to override
    object.Equals(object)
    method, but that's just one way to satisfy the system. We also must overload Equals with more specific matchings, in our case that's another QuasiEnum subtype. In this way we circumvent having to unbox
    object
    .

    Another thing worth noting is that our type is reference type, so we must be aware that the incoming object may be
    null
    . This is even more important later, when we'll override the static equality operators
    ==
    and
    !=
    .

    Regardless, here we have to decide, which one is better: a) to rely strictly on the actual identity of the object, or b) to rely only on its name? Well the actual C# enums rely on comparing their values, so I'm going to compare the names instead. But no hard reference match, I think that can't work because of serialization anyway. Strictly speaking, enum values should behave like value types.

    Let's quickly introduce a method to reliably match names from wherever we need to
    Code (csharp):
    1. static public bool StringsMatch(string str1, string str2)
    2.   => string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);
    And then
    Code (csharp):
    1. public bool Equals(QuasiEnum other)
    2.   => other is not null && StringsMatch(this.Name, other.name);
    Finally, we want the method
    Equals
    to work with anything that makes sense, so matching against another
    QuasiEnum
    , another name (
    string
    ), or another value (
    int
    ), are all valid. If the incoming object is of the unsupported type (or
    null
    ), then it's an automatic mismatch. (The following code is known as switch expression btw.)
    Code (csharp):
    1. public override bool Equals(object obj)
    2.   => obj switch {
    3.       QuasiEnum other => Equals(other),
    4.       int val => this == val,
    5.       string str => this == str,
    6.       {} => false
    7.     };
    "Checking against these other values, how's that supposed to work?"

    Going there, we're doing custom static equality operators next. With them we need to make sure neither of the objects are
    null
    , and if they're both
    null
    , the check should return
    true
    . We can test this null equality with
    bool ReferenceEquals(...)
    inherited from
    object
    . Within these operators it's silly to attempt
    a == null
    , that would probably just lead to stack overflow.

    Basically, if left-hand-side is non-null, it's safe to proceed with Equals test we made before. And if it's null, return true only if the right-hand-side is null as well.
    Code (csharp):
    1. static public bool operator ==(QuasiEnum a, QuasiEnum b)
    2.   => ReferenceEquals(a, null)? ReferenceEquals(b, null) : a.Equals(b);
    3.  
    4. // strings can be null as well (even though they count as value types)
    5. static public bool operator ==(QuasiEnum qenum, string str)
    6.   => ReferenceEquals(qenum, null)? ReferenceEquals(str, null)
    7.                                  : StringsMatch(qenum.Name, str);
    8.  
    9. // other value types can't be null, they have default values (i.e. 0 in this case)
    10. static public bool operator ==(QuasiEnum qenum, int val)
    11.   => ReferenceEquals(qenum, null)? false : qenum.Value.Equals(val);
    And since
    ==
    operators need to have their matching counterparts, we make sure they stay consistent
    Code (csharp):
    1. static public bool operator !=(QuasiEnum a, QuasiEnum b) => !(a == b);
    2. static public bool operator !=(QuasiEnum qenum, string str) => !(qenum == str);
    3. static public bool operator !=(QuasiEnum qenum, int val) => !(qenum == val);
    Next up,
    IComparable
    . That's just
    Code (csharp):
    1. public int CompareTo(QuasiEnum other) => value.CompareTo(other.Value);
    and while we're at it, let's do GetHashCode as well
    Code (csharp):
    1. public override int GetHashCode() => GetType().GetHashCode() ^ Value.GetHashCode();
    Let's now do more pressing things, things that have to do with our
    static readonly
    item collection.
    This is going to be the core method to scan the internals of our derived class and the only way to make this work is via reflection (add using System.Reflection; to the top).
    Code (csharp):
    1. static IEnumerable<FieldInfo> enumerableStaticFieldsOf<T>() where T : QuasiEnum {
    2.   const BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
    3.   var fields = typeof(T).GetFields(flags); // fetch the list of all such fields
    4.   if(fields is not null)
    5.     for(int i = 0; fields.Length; i++)
    6.       yield return fields[i];
    7. }
    I will constrain T to QuasiEnum in many such methods throughout the solution. This is so only derivations are accepted (QuasiEnum itself is
    abstract
    so you can't instantiate that directly).

    The method above will help us
    foreach
    through all static fields within the type T, when we need it. Now we can use this to create two different publicly-available methods that should work with all QuasiEnum derivations in general. The first one
    GetItemsOf<T>
    provides another IEnumerable to let us foreach through the items, and the other
    GetNamesOf<T>
    returns a fixed array of all their names. The exact order is undefined.
    Code (csharp):
    1. static public IEnumerable<T> GetItemsOf<T>() where T : QuasiEnum {
    2.   foreach(var info in enumerableStaticFieldsOf<T>()) {
    3.     var value = info.GetValue(null) as T;
    4.     if(value is not null) yield return value;
    5.   }
    6. }
    (
    using System.Collections.Generic;
    )
    Code (csharp):
    1. static public string[] GetNamesOf<T>() where T : QuasiEnum {
    2.   var names = new List<string>();
    3.   foreach(var info in enumerableStaticFieldsOf<T>()) {
    4.     var value = info.GetValue(null) as T;
    5.     if(value is not null) names.Add(value.Name);
    6.   }
    7.   return names.ToArray();
    8. }
    It's almost done. Now we have the means of traversing through all internally declared items, but they must satisfy two things: 1) the type, 2)
    static public
    declaration. We should now finish the heart of the system, the way to find a specific object instance once we know its type and name (or value). I'll write this in a LINQ-esque manner, so let's start with the general predicate search.
    Code (csharp):
    1. static T firstMatchOrDefault<T>(IEnumerable<T> enumerable, Func<T, bool> predicate) where T : QuasiEnum {
    2.   T item = default;
    3.   foreach(var x in enumerable)
    4.     if(predicate(x)) { item = x; break; }
    5.   return item;
    6. }
    This allows us to define a robust selection method
    Code (csharp):
    1. static T selectWhere<T>(Func<T, bool> predicate) where T : QuasiEnum
    2.   => firstMatchOrDefault(GetItemsOf<T>(), predicate);
    Leading us naturally to our protected interface, to be used by user derivations
    Code (csharp):
    1. static protected T GetByName<T>(string name) where T : QuasiEnum
    2.   => selectWhere<T>( item => StringsMatch(item.Name, name) );
    3.  
    4. static protected T GetByValue<T>(int value) where T : QuasiEnum
    5.   => selectWhere<T>( item => item.Value == value );
    Just a couple more utility functions to help us explicitly cast as well as implicitly pass our QuasiEnum objects as string arguments, and we can wrap this up.
    Code (csharp):
    1. static public T Cast<T>(QuasiEnum qenum) where T : QuasiEnum => GetByName<T>(qenum.Name);
    2. static public T Cast<T>(string str) where T : QuasiEnum => GetByName<T>(str);
    3. static public T Cast<T>(int value) where T : QuasiEnum => GetByValue<T>(value);
    4.  
    5. static public implicit operator string(QuasiEnum qenum) => qenum.Name;
    6.  
    7. // and let's not forget
    8. public override string ToString() => this; // lol, now this is just showing off
    Ok, so the core class is done! But there are some things which can be slightly improved. Let's think about the user side. The user derives from QuasiEnum, declares the fields, sets the names etc. The user can write a private constructor from which it becomes very easy to build a list of all locally defined names. Thanks to the reflection code above, this isn't mandatory, but IF the user sets this up, it would be nice if he could deliver this list, because that's how we can completely avoid having to use reflection during run-time (edit: reflection can be slow and messy compared to regular means of searching and method invocation, especially when used in games).

    So let's change our
    selectWhere
    to
    Code (csharp):
    1. static T selectWhere<T>(Func<T, bool> predicate, IList<T> list) where T : QuasiEnum
    2.   => firstMatchOrDefault(list?? GetItemsOf<T>(), predicate);
    And expand our protected interface like so
    Code (csharp):
    1. static protected T GetByName<T>(string name, IList<T> list = null) where T : QuasiEnum
    2.   => selectWhere<T>( item => StringsMatch(item.Name, name) , list);
    3.  
    4. static protected T GetByValue<T>(int value, IList<T> list = null) where T : QuasiEnum
    5.   => selectWhere<T>( item => item.Value == value , list);
    Let's check what this looks like on the
    MyEnum
    side.
    Code (csharp):
    1. public class MyEnum : QuasiEnum {
    2.  
    3.   // we can now put the tools we've built so far to good use
    4.   static public List<MyEnum> GetAll()
    5.     => new List<MyEnum>(GetItemsOf<MyEnum>());
    6.  
    7.   static public MyEnum GetByName(string name) => GetByName<MyEnum>(name);
    8.   static public MyEnum GetByValue(int value) => GetByValue<MyEnum>(value);
    9.  
    10.   // to mimic standard enum behavior
    11.   static public explicit operator MyEnum(int value) => GetByValue(value);
    12.  
    13.   static public readonly MyEnum zero = new MyEnum("zero", 0);
    14.   static public readonly MyEnum first = new MyEnum("one", 1);
    15.   static public readonly MyEnum second = new MyEnum("two", 2);
    16.   static public readonly MyEnum third = new MyEnum("three", 3);
    17.   static public readonly MyEnum fourth = new MyEnum("four", 4);
    18.   static public readonly MyEnum fifth = new MyEnum("five", 5);
    19.  
    20.   // constructor doesn't do anything at this point
    21.   private MyEnum(string name, int value) : base(name, value) {}
    22.  
    23. }
    So what has to change if
    MyEnum
    decides to support the local list to avoid having to use reflection?
    Code (csharp):
    1. public class MyEnum : QuasiEnum {
    2.  
    3.   // NOTE: this definition MUST be above the actual static readonly fields
    4.   static List<MyEnum> _enums = new List<MyEnum>();
    5.  
    6.   // we can now change this
    7.   static public MyEnum[] GetAll() => _enums.ToArray(); // don't forget we need a defensive copy anyway
    8.  
    9.   // and we can supply the local list where it's needed
    10.   static public MyEnum GetByName(string name) => GetByName<MyEnum>(name, _enums);
    11.   static public MyEnum GetByValue(int value) => GetByValue<MyEnum>(value, _enums);
    12.  
    13.   // static public readonly ...
    14.   // static public readonly ...
    15.   // static public readonly ...
    16.  
    17.   private MyEnum(string name, int value) : base(name, value) {
    18.     _enums.Add(this); // they all gather nicely here
    19.   }
    20.  
    21. }
    That's not too much work, right? Also you can derive from this class again (edit: and we will by the end of this exercise). If you're wondering how can you inherit static fields, well, you can define the superclass, and then simply redirect all subclass queries toward its definition instead. But I haven't played much with this (I did with the nested types, that part works as expected), the above solution was something I was happy with, and it's perfectly maintainable the way it is.

    Oh and wouldn't it be nice if we could save some extra info, something that makes more sense than having to repeat the name of the field, like a tooltip, or a display name of sorts? Auto-generating names would also be nice to have. Because if you think about it, changing a field's name is a huge pain in the back, because you can forget to match the two. Currently, the two are completely disjointed and
    MyEnum.fourth
    has the string value of "four" which is actually cool in a serialization context, as you can change fourth to usedToBeFourth and it will still deserialize correctly. So there are benefits to be had on both sides of the coin.

    I decided that the names should match at compile-time. But here's the problem, I don't have any control over how and when the compiler is going to swoop through our readonlys. So the poor man's solution was to place
    nameof
    in each instantiation.
    Code (csharp):
    1. static public readonly MyEnum second = new MyEnum(nameof(second), 2);
    This way you could at least rename a field and the name would always match it, but I wasn't really satisfied with this solution, that's just crazy. So I played dirty instead and assumed that the most logical thing a compiler would do would be to process the whole readonly block in the most optimal order there is: top to bottom. There are no guarantees this is the case however, and this might break unexpectedly, but let's play with it, so far it's been very reliable.

    First, we add AutoGenerateNames to
    QuasiEnum
    class
    Code (csharp):
    1. static protected T AutoGenerateNames<T>() where T : QuasiEnum {
    2.   foreach(var info in enumerableStaticFieldsOf<T>()) {
    3.     var value = info.GetValue(null) as T;
    4.     if(value?.Name == "") value.Name = info.Name;
    5.   }
    6.   return default;
    7. }
    This way we only fill in the name if the name was already provided blank (""). This allows the user class to define name overrides. Now we can cheese the compiler. Back to
    MyEnum

    Code (csharp):
    1. static public readonly MyEnum zero = new MyEnum("", 0);
    2. static public readonly MyEnum first = new MyEnum("", 1);
    3. static public readonly MyEnum second = new MyEnum("", 2);
    4. static public readonly MyEnum third = new MyEnum("", 3);
    5. static public readonly MyEnum fourth = new MyEnum("four", 4);
    6. static public readonly MyEnum fifth = new MyEnum("", 5);
    7. static private object _ = AutoGenerateNames<MyEnum>(); // BAM
    Wholesome, isn't it? Here I've deliberately set the
    fourth
    's name to "four".
    (Edit: the way this works is overhauled in the latest version available at the end of the article. This version can also auto-define the fields, letting you avoid having to manually create objects with
    new
    )

    Let's introduce another constructor for this particular case, and then we can try and tackle extra data and future-proof some basic support for custom display names.
    Code (csharp):
    1. // back in QuasiEnum
    2. protected QuasiEnum(int value) : this("", value) {}
    This improves legibility of MyEnum
    Code (csharp):
    1. public class MyEnum : QuasiEnum {
    2.  
    3.   // ...
    4.  
    5.   static public readonly MyEnum zero = new MyEnum(0, "zero is naughty");
    6.   static public readonly MyEnum first = new MyEnum(1, "first is straight");
    7.   static public readonly MyEnum second = new MyEnum(2, "second is too late");
    8.   static public readonly MyEnum third = new MyEnum(3, "third is a charm");
    9.   static private object _ = AutoGenerateNames<MyEnum>();
    10.  
    11.   string _description;
    12.  
    13.   private MyEnum(int value, string description) : base(value) {
    14.     _enums.Add(this);
    15.     _description = description;
    16.   }
    17.  
    18.   public string DisplayName => _description;
    19.  
    20. }
    Ok so this is pretty extensible. The solution is now working in code and can be used as is. But we still want to support custom serialization and integrate the whole thing with Unity editors.

    Serialization
    Well, this part is fairly simple to implement.
    Let's add the following method to QuasiEnum class. This will allow us to examine what is being read from the file and to react accordingly.
    (Also add using
    Debug = UnityEngine.Debug;
    to top.)
    Code (csharp):
    1. protected void ParseDeserialized<T>(string str, List<T> list = null, bool allowInvalid = false, bool suppressLog = false) where T : QuasiEnum {
    2.   var parsed = GetByName<T>(str, list);
    3.  
    4.   if(parsed is not null) {
    5.     (Name, Value) = ( parsed.Name, parsed.Value );
    6.   } else if(allowInvalid) {
    7.     if(!suppressLog) Debug.LogWarning($"Warning: {typeof(T).Name} had invalid deserialization data.");
    8.     (Name, Value) = ( null, -1 );
    9.   } else {
    10.     throw new InvalidOperationException($"Unrecognized data '{str}'.");
    11.   }
    12. }
    First, the user class itself has to be marked for serialization. Then it should implement
    ISerializationCallbackReceiver
    . We then introduce a serialized field called
    name
    which will be stored to YAML. This word is a reserved keyword in C# however, so we'll have to use verbatim syntax (
    @
    ).
    (edit: this was a mistake on my part, no it's not reserved, everything's fine.)
    Code (csharp):
    1. [Serializable]
    2. public class MyEnum : QuasiEnum, ISerializationCallbackReceiver {
    3.  
    4.   // static readonly fields go here ...
    5.  
    6.   [SerializeField] string name; // must be called 'name' because the drawer relies on this
    7.  
    8.   void ISerializationCallbackReceiver.OnBeforeSerialize()
    9.     => name = this;
    10.  
    11.   void ISerializationCallbackReceiver.OnAfterDeserialize()
    12.     => ParseDeserialized<MyEnum>(name, list: _enums, allowInvalid: true);
    13.  
    14.   ...

    SimpleSanitizer
    Before we proceed with the custom property drawer, we're going to need a utility to sanitize and beautify our auto-generated names, in a manner similar to what Unity does when it builds an auto-inspector. Namely it introduces spaces between camelCase words, capitalizes letters, and removes underscore characters. We can do that as well. I won't explain this code too much, but in a nutshell we have a simple state tracker (
    ScannerState
    ) and a simple string scanner (
    Process
    method) that runs through the string and produces a better copy of it in one go.
    Code (csharp):
    1. using System.Text;
    2.  
    3. namespace StringSanitizers {
    4.  
    5.   static public class SimpleSanitizer {
    6.  
    7.     static public string Process(string src) {
    8.       if(string.IsNullOrWhiteSpace(src)) return src?.Trim();
    9.  
    10.       var scan = new Utils.ScannerState();
    11.  
    12.       for(int i = 1; i <= src.Length; i++) {
    13.  
    14.         scan.Sample(src[i-1], (i < src.Length)? src[i] : default);
    15.  
    16.         if(scan.curr.IsUScor()) scan.curr = Utils.SPACE;
    17.           else scan.curr = scan.TryCaps(scan.curr);
    18.  
    19.         if(scan.curr.IsSpace()) scan.TrySpace();
    20.           else scan.Append(scan.curr);
    21.  
    22.         if(scan.next == default) break; // no look-ahead
    23.  
    24.         if(lower_upper_pair() || any_one_digit())
    25.           scan.TrySpace();
    26.  
    27.       }
    28.  
    29.       return scan.sb.ToString();
    30.  
    31.       bool lower_upper_pair() => scan.curr.IsLower() &&  scan.next.IsUpper();
    32.       bool any_one_digit()    => scan.curr.IsDigit() && !scan.next.IsDigit() ||
    33.                                 !scan.curr.IsDigit() &&  scan.next.IsDigit();
    34.     }
    35.  
    36.   }
    37.  
    38.   static class Utils {
    39.  
    40.     public const char SPACE = ' ';
    41.  
    42.     static public bool IsUScor(this char chr) => chr == '_';
    43.     static public bool IsSpace(this char chr) => chr == Utils.SPACE;
    44.     static public bool IsDigit(this char chr) => chr >= '0' && chr <= '9';
    45.     static public bool IsLower(this char chr) => char.IsLetter(chr) && char.IsLower(chr);
    46.     static public bool IsUpper(this char chr) => char.IsLetter(chr) && char.IsUpper(chr);
    47.     static public bool IsPunct(this char chr) => char.IsPunctuation(chr);
    48.  
    49.     public class ScannerState {
    50.  
    51.       public char curr, next;
    52.  
    53.       public readonly StringBuilder sb;
    54.       public bool shift = true;
    55.  
    56.       public ScannerState() => sb = new StringBuilder();
    57.  
    58.       public void Sample(char a, char b) => (curr, next) = (a, b);
    59.  
    60.       public void Append(char x) => sb.Append(x);
    61.  
    62.       public void TrySpace() {
    63.         if(!shift) Append(Utils.SPACE);
    64.         shift = true;
    65.       }
    66.  
    67.       public char TryCaps(char x) {
    68.         if(shift) {
    69.           if(x != Utils.SPACE) shift = false;
    70.           if(x.IsLower()) return char.ToUpperInvariant(x);
    71.         }
    72.         return x;
    73.       }
    74.  
    75.     }
    76.  
    77.   }
    78.  
    79. }
    We'll also need these to chop some strings later, it's just an extract from my custom extensions. In my environment they sit in their respective libraries, but I'll have to think twice about where to put them when I dump the code in its entirety.
    Code (csharp):
    1. static public bool CropLeft(this string s, int index, out string result) {
    2.   result = s.CropLeft(index);
    3.   return index > 0 && index < s.Length;
    4. }
    5.  
    6. static public string CropLeft(this string s, int index)
    7.   => (s is null)? null : s.Substring(0, index.Clamp(s.Length + 1));
    8.  
    9. // and this is here only because I refuse to use any kind of Math lib in this solution
    10. static int Clamp(this int v, int count) => Clamp(v, 0, count - 1);
    11. static int Clamp(this int v, int min, int max) => (v <= max)? (v > min)? v : min : max;
    (Edit: You can find all of this settled down in the latest version source code.)

    Phew, now we're ready to start untangling the property drawer.

    QuasiEnumDrawer
    I hate writing drawers, but this one is not that big, honestly, ~200 lines of code. I'll go backwards, it'll be easier to parse. First, let's consider what features we want to implement. How about the ability to show values next to the name and/or the type of the custom enum? And what about optional support for that DisplayName getter we introduced above? I've also added the possibility of having a 'default' entry, like 'undefined' or 'None'. Why should you have to add that to your enum, that's not data, that's a selector state? Oh oh, and sorting features, we can sort by value, or by name, or leave it unsorted.

    Ok then, so let's make a couple of enums to remind ourselves what to include. Let's bother with how to supply them later. This is btw a legit use of standard enums in C# and Unity. You just shouldn't describe game logic with them.
    Code (csharp):
    1. [Flags]
    2. public enum QuasiEnumOptions {
    3.   None = 0,
    4.   ShowValue = 0x1,             // Shows value, in format: name (value)
    5.   ShowTypeInLabel = 0x2,       // Shows type in label
    6.   IncludeSelectableNone = 0x4, // Adds selectable zeroth "None" element if the list is non-empty
    7.   UseDisplayName = 0x8,        // Uses the locally-defined DisplayName getter for display names
    8. }
    9.  
    10. public enum QuasiEnumSorting {
    11.   Unsorted = 0,
    12.   ByName,
    13.   ByValue
    14. }
    Let's begin with the foundation.
    We need this to keep track of everything, just a simple immutable struct holding what we have right now.
    Code (csharp):
    1. readonly struct RecordRow {
    2.   public readonly string name;
    3.   public readonly int value;
    4.   public readonly string display;
    5.  
    6.   public RecordRow(string name, int value, string display)
    7.     => (this.name, this.value, this.display) = (name, value, display);
    8. }
    Some general utilities we're gonna need
    Code (csharp):
    1. // this is just to shorten this monstrosity
    2. bool isNullOrWhite(string s) => string.IsNullOrWhiteSpace(s);
    3.  
    4. // this one will be handy, array alloc with a lambda filler
    5. T[] newArray<T>(int len, Func<int, T> lambda) {
    6.   var d = new T[len];
    7.   if(lambda is not null)
    8.     for(int i = 0; i < len; i++) d[i] = lambda(i);
    9.   return d;
    10. }
    11.  
    12. // finally, because we're going to use a local dictionary to help us find an index in O(1)
    13. int indexOfRecord(string name) {
    14.   if(!_lookup.TryGetValue(name, out var index)) index = -1;
    15.   return index;
    16. }
    At the beginning, we want to introduce some standard strings.
    Code (csharp):
    1. static readonly string _displayName_method = "DisplayName"; // prescribed name of the getter
    2. static readonly string _none_string = "(None)"; // for the extra 'None' selection field
    3. static readonly string[] _empty_array = new string[] { "(Empty)" }; // when there are no names at all
    We can now build our records, one row at a time, where each row represents one item. Don't worry about that
    dynamic
    declaration, I'll get back to it.
    Code (csharp):
    1. RecordRow buildRecordRow(dynamic item, Type type, QuasiEnumOptions options) {
    2.   const BindingFlags flags = BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.DeclaredOnly |
    3.                  BindingFlags.FlattenHierarchy | BindingFlags.Instance; // this is to fetch that getter
    4.  
    5.   var display = string.Empty;
    6.  
    7.   // optionally consider the local DisplayName getter
    8.   if(options.HasFlag(QuasiEnumOptions.UseDisplayName))
    9.     display = type.GetProperty(_displayName_method, flags)?.GetValue(item);
    10.  
    11.   // fall back to basic name sanitation
    12.   if(isNullOrWhite(display))
    13.     display = SimpleSanitizer.Process(item.Name);
    14.  
    15.   // optionally append value
    16.   if(options.HasFlag(QuasiEnumOptions.ShowValue))
    17.     display = $"{display} ({item.Value})";
    18.  
    19.   return new RecordRow(item.Name, item.Value, display);
    20. }
    Nice. Now, the trick is to somehow fetch the values from
    GetNamesOf<T>
    method back in QuasiEnum. But this is easier said than done, because it's a generic code that also implies covariance. Long story short, I've managed to properly address it, but to fully satisfy the compiler, I had to declare the result as
    dynamic
    in the end. There is probably a better solution, but I'm not bothered too much, I find this relatively appropriate for this scenario.

    Here we supply a target type, and fetch back the list of names (note that we can't just scan for readonlys again, because the user had ample opportunity to format his entries in a way that is unknown to us here).
    Code (csharp):
    1. dynamic enumerableNamesViaReflection(Type type) {
    2.   const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly;
    3.   var method = typeof(QuasiEnum).GetMethod(nameof(QuasiEnum.GetItemsOf), flags).MakeGenericMethod(type);
    4.   return method.Invoke(null, null); // static context, parameterless
    5. }
    This was the biggest hurdle. Let's now build the records table in its entirety.
    Code (csharp):
    1. // will return an empty array at the very least
    2. RecordRow[] buildRecords(Type type, QuasiEnumOptions options, QuasiEnumSorting sorting) {
    3.   var table = new List<RecordRow>();
    4.  
    5.   // add the rows
    6.   foreach(var item in enumerableNamesViaReflection(type))
    7.     table.Add(buildRecordRow(item, type, options));
    8.  
    9.   // sort the rows
    10.   table.Sort( (a,b) => comparison(a, b, sorting) );
    11.  
    12.   // insert 'None' field
    13.   if(options.HasFlag(QuasiEnumOptions.IncludeSelectableNone))
    14.     table.Insert(0, new RecordRow(null, -1, _none_name)); // insert a deliberately invalid entry
    15.  
    16.   // build the index lookup after everything has settled down
    17.   _lookup = new Dictionary<string, int>();
    18.   for(int i = 0; i < table.Count; i++)
    19.     _lookup[table[i].Name] = i;
    20.  
    21.   return table.ToArray(); // finished
    22.  
    23.   // just a local function to aid us with sorting
    24.   int comparison(RecordRow a, RecordRow b, QuasiEnumSorting sorting)
    25.     => sorting switch {
    26.            QuasiEnumSorting.ByName => string.CompareOrdinal(a.display, b.display),
    27.            QuasiEnumSorting.ByValue => a.value.CompareTo(b.value),
    28.            _ => 0
    29.         }
    30. }
    With all that done we can properly address the body of the drawer. Here I'm showing the script in full glory.
    Code (csharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Reflection;
    4. using StringSanitizers;
    5. using UnityEngine;
    6. using UnityEditor;
    7.  
    8. // useForChildren is supposed to mean child classes
    9. [CustomPropertyDrawer(typeof(QuasiEnum), useForChildren: true)]
    10. public class QuasiEnumDrawer : PropertyDrawer {
    11.  
    12.   // we have already defined static readonly strings here
    13.  
    14.   SerializedProperty _targetProperty;
    15.  
    16.   RecordRow[] _records;            // never null (except on start)
    17.   Dictionary<string, int> _lookup; // used for fast index-of-record lookup
    18.   string[] _displayNames;          // cached for EditorGUI.Popup
    19.  
    20.   public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label) {
    21.     // settings are manually tweakable for now
    22.     var (type, options, sorting) = ( fieldInfo.FieldType, QuasiEnumOptions.None, QuasiEnumSorting.ByValue );
    23.  
    24.     _targetProperty = property.FindPropertyRelative("name"); // this hinges on that serialized field
    25.     if(_targetProperty is null) return; // and if that's absent we have no other option but to bail
    26.                                        // I could handle this with more grace, maybe show something else?
    27.  
    28.     if(_records is null) // we check if this was initialized
    29.       _records = buildRecords(type, options, sorting)
    30.  
    31.     var val = indexOfRecord(_targetProperty.stringValue);
    32.  
    33.     if(options.HasFlag(QuasiEnumOptions.ShowTypeInLabel))
    34.       label.text = !isNullOrWhite(label.text)? $"{label.text} ({type.Name})" : type.Name;
    35.  
    36.     var savedIndent = EditorGUI.indentLevel;
    37.     label = EditorGUI.BeginProperty(rect, label, property);
    38.  
    39.       rect = EditorGUI.PrefixLabel(rect, GUIUtility.GetControlID(FocusType.Passive), label);
    40.       EditorGUI.indentLevel = 0; // after indenting label, cancel indentation entirely
    41.  
    42.       if(nonEmptyRecords(options)) {
    43.         var newVal = drawDropDownSelector(rect, val.Clamp(_records.Length));
    44.         if(val != newVal) _targetProperty.stringValue = _records[newVal].name;
    45.  
    46.       } else { // make the drop down appear empty and disabled
    47.         disabledGUI( () => EditorGUI.Popup(rect, 0, _empty_array) );
    48.         targetProperty.stringValue = string.Empty;
    49.  
    50.       }
    51.  
    52.     EditorGUI.EndProperty();
    53.     EditorGUI.indentLevel = savedIndent;
    54.  
    55.     // let's do the local functions after this line to reduce the clutter above
    56.  
    57.     // this allows us to track states between two pieces of bread in a sandwich
    58.     // a useful pattern that ensures minimum mess when writing IMGUI code
    59.     void disabledGUI(Action action) {
    60.       var saved = GUI.enabled;
    61.       GUI.enabled = false;
    62.       action.Invoke();
    63.       GUI.enabled = saved;
    64.     }
    65.  
    66.     int drawDropDownSelector(Rect rect, int selected)
    67.       => EditorGUI.Popup(rect, selected, _displayNames??= extractDisplayColumn());
    68.  
    69.     string[] extractDisplayColumn()
    70.       => newArray(_records.Length, i => _records[i].display );
    71.  
    72.     // if the list was empty, "None" that was optionally added shouldn't count
    73.     bool nonEmptyRecords(QuasiEnumOptions options)
    74.       => _records.Length - (options.HasFlag(QuasiEnumOptions.IncludeSelectableNone)? 1 : 0) > 0;
    75.  
    76.   }
    77.  
    78.   // the rest of the code we did before
    79.  
    80. }

    Inspecting arrays
    The solution above does not play well with serialized arrays. Well crap.
    Another round then. First, we want to detect whether this property belongs to an array property, and if so, which element index it was assigned to. Both of these are another of the local functions in OnGUI. I can't help it, they don't belong anywhere else.

    With detectArrayProperty all I do here is splice up the actual property path, sniff out the parent object, double-check it's an array, and return it. We do this only once.
    Code (csharp):
    1. SerializedProperty detectArrayProperty() {
    2.   if(property.name == "data") { // I.e. propertyPath = "myName.Array.data[3]"
    3.     var path = property.propertyPath;
    4.     if(path.CropLeft(path.LastIndexOf(".Array"), out var actualName)) { // "myName"
    5.       var p = property.serializedObject.FindProperty(actualName);
    6.       if(p.isArray) return p;
    7.     }
    8.   }
    9.   return null;
    10. }
    We also need to get the element index. This is just a brute force search, not a pretty sight. I'm still looking into ways to improve this. But this will only encumber the inspector if the array is huge (and unfolded).
    Code (csharp):
    1. int getArrayPropertyIndex(SerializedProperty arrayProperty) {
    2.   if(arrayProperty is null) return -1; // just a sanity check
    3.   for(int i = 0; i < arrayProperty.arraySize; i++)
    4.     if(SerializedProperty.EqualContents(arrayProperty.GetArrayElementAtIndex(i), property))
    5.       return i;
    6.   return -1;
    7. }
    Let's also introduce mixed value display, for multi-value editing. I won't make it work-work, but I cannot completely neglect it either. I'm not sure how Unity treats multi-value drop downs, but there is not much one can do anyway.
    Code (csharp):
    1. // yet another sandwich method
    2. void mixedGUI(bool condition, Action action) {
    3.   var saved = EditorGUI.showMixedValue;
    4.   EditorGUI.showMixedValue = condition;
    5.   action.Invoke();
    6.   EditorGUI.showMixedValue = saved;
    7. }
    we add another SerializedProperty class field
    Code (csharp):
    1. SerializedProperty _targetProperty;
    2. SerializedProperty _arrayProperty;
    Next we go back to OnGUI
    Code (csharp):
    1.     ...
    2.  
    3.     if(_records is null) {
    4.       _records = buildRecords(type, options, sorting);
    5.       _arrayProperty = detectArrayProperty();
    6.     }
    7.  
    8.     var val = indexOfRecord(_targetProperty.stringValue);
    9.  
    10.     if(_arrayProperty is not null) {
    11.       if(string.Equals(label.text, _targetProperty.stringValue, StringComparison.InvariantCulture))
    12.         label.text = $"Element {getArrayPropertyIndex(_arrayProperty)}";
    13.     } else {
    14.       if(options.HasFlag(QuasiEnumOptions.ShowTypeInLabel))
    15.         label.text = !isNullOrWhite(label.text)? $"{label.text} ({type.Name})" : type.Name;
    16.     }
    17.  
    18.     var savedIndent = EditorGUI.indentLevel;
    19.  
    20.     ...
    21.  
    22.       if(nonEmptyRecords(options)) {
    23.         mixedGUI(_targetProperty.hasMultipleDifferentValues, () => {
    24.           var newVal = drawDropDownSelector(rect, val.Clamp(_records.Length));
    25.           if(val != newVal) _targetProperty.stringValue = _records[newVal].name;
    26.         });
    27.  
    28.       } else { // make the drop down empty and disabled
    29.         disabledGUI( () => EditorGUI.Popup(rect, 0, _empty_array) );
    30.         targetProperty.stringValue = string.Empty;
    31.  
    32.       }
    33.  
    34.   ...
    Edit: The drawer was changed slightly in the latest version. Most of this still holds true however.

    Custom Attribute

    Lastly, we ought to introduce a custom attribute. This will allow us to supply the missing options (as metadata).

    Code (csharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)]
    5. public class QuasiEnumAttribute : PropertyAttribute {
    6.  
    7.   public readonly Type type;
    8.   public readonly QuasiEnumOptions options;
    9.   public readonly QuasiEnumSorting sorting;
    10.  
    11.   public QuasiEnumAttribute(Type type)
    12.     : this(type, QuasiEnumOptions.None, QuasiEnumSorting.ByValue) {}
    13.  
    14.   public QuasiEnumAttribute(Type type, QuasiEnumSorting sorting)
    15.     : this(type, QuasiEnumOptions.None, sorting) {}
    16.  
    17.   public QuasiEnumAttribute(Type type, QuasiEnumOptions options, QuasiEnumSorting.sorting) {
    18.     if(!type.IsSubclassOf(typeof(QuasiEnum))
    19.       throw new ArgumentException($"{nameof(QuasiEnumAttribute)} works only with subtypes of {nameof(QuasiEnum)}.");
    20.  
    21.     (this.type, this.options, this.sorting) = (type, options, sorting);
    22.   }
    23. }
    This lets us fully describe the MyEnum field in our production code.
    For example
    Code (csharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. public class QuasiEnumTest : MonoBehaviour {
    5.  
    6.   [SerializeField]
    7.   [QuasiEnum(typeof(MyEnum), QuasiEnumOptions.ShowValue | QuasiEnumOptions.IncludeSelectableNone, QuasiEnumSorting.ByName)]
    8.   MyEnum _enum; // try also MyEnum[] _enum;
    9.  
    10. }
    But we do have to register this data in our drawer to make this work.
    Code (csharp):
    1. [CustomPropertyDrawer(typeof(QuasiEnumAttribute))]
    2. [CustomPropertyDrawer(typeof(QuasiEnum), useForChildren: true)]
    3. public class QuasiEnumDrawer : PropertyDrawer {
    4.  
    5.   ...
    6.  
    7.   public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label) {
    8.     var attrib = this.attribute as QuasiEnumAttribute;
    9.  
    10.     var (type, options, sorting) = (attrib is null)? ( fieldInfo.FieldType, QuasiEnumOptions.None, QuasiEnumSorting.ByValue )
    11.                                                    : ( attrib.type, attrib.options, attrib.sorting );
    12.  
    13.     ...
    14.  
    15.   }
    16.  
    17.   ...
    18.  
    19. }
    Edit: In the latest version, the attribute does not work on the actual field anymore, but on the class instead. This is because I've added settings to how the type itself is treated (for example a setting to auto-define the fields etc). There is also a possibility I will make two separate attributes in the final version, because you might want to have two serialized fields for the same type, one that accepts 'None' and the other that doesn't, as an example. I'm still thinking about it.

    Tooltips
    As a bonus let's add support for tooltips as well. We can start by attacking the underlying data.
    Code (csharp):
    1. [Flags]
    2. public enum QuasiEnumOptions {
    3.   None = 0,
    4.   ShowValue = 0x1,             // Shows value, in format: name (value)
    5.   ShowTypeInLabel = 0x2,       // Shows type in label
    6.   IncludeSelectableNone = 0x4, // Adds selectable zeroth "None" element if the list is non-empty
    7.   UseDisplayName = 0x8,        // Uses the locally-defined DisplayName getter for display names
    8.   UseTooltipString = 0x10      // Uses the locally-defined TooltipString getter for item tooltips
    9. }
    Code (csharp):
    1. RecordRow buildRecordRow(dynamic item, Type type, QuasiEnumOptions options) {
    2.  
    3.   var display = string.Empty;
    4.   var tooltip = default(string);
    5.   ...
    6.  
    7.   // optionally consider the local DisplayName getter
    8.   if(options.HasFlag(QuasiEnumOptions.UseDisplayName))
    9.     display = type.GetProperty(_displayName_method, flags)?.GetValue(item);
    10.  
    11.   // optionally consider the local TooltipString getter
    12.   if(options.HasFlag(QuasiEnumOptions.UseTooltipString)) // new flag
    13.     tooltip = type.GetProperty(_tooltipName_method, flags)?.GetValue(item); // new getter
    14.   ...
    15.  
    16.   return new RecordRow(item.Name, item.Value, display, tooltip); // modified c-tor
    17. }
    Code (csharp):
    1. readonly struct RecordRow {
    2.   public readonly string name;
    3.   public readonly int value;
    4.   public readonly string display;
    5.   public readonly string tooltip; // new field
    6.  
    7.   public RecordRow(string name, int value, string display, string tooltip = null)
    8.     => (this.name, this.value, this.display, this.tooltip) = (name, value, display, tooltip);
    9. }
    Then,
    Code (csharp):
    1. ...
    2.  
    3. public class QuasiEnumDrawer : PropertyDrawer {
    4.  
    5.   static readonly string _displayName_method = "DisplayName";
    6.   static readonly string _tooltipName_method = "TooltipString";
    7.  
    8.   ...
    9.  
    10.   RecordRow[] _records;            // never null (except on start)
    11.   Dictionary<string, int> _lookup; // used for fast index-of-record lookup
    12.   string[] _displayNames;          // cached for EditorGUI.Popup
    13.   GUIContent[] _guiContent;        // same as _displayNames, but for tooltips
    14.  
    15.   public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label) {
    16.     ...
    17.     var newVal = drawDropDownSelector(rect, val.Clamp(_records.Length), options.HasFlag(QuasiEnumOptions.UseTooltipString));
    18.     ...
    19.  
    20.     int drawDropDownSelector(Rect rect, int selected, bool usesTooltips)
    21.       => !usesTooltips? EditorGUI.Popup(rect, selected, _displayNames??= extractDisplayColumn())
    22.                       : EditorGUI.Popup(rect, GUIContent.none, selected, _guiContent??= extractGUIContent());
    23.  
    24.     ...
    25.  
    26.     GUIContent[] extractGUIContent() // I told you newArray was handy
    27.       => newArray(_records.Length, i => new GUIContent(_records[i].display, _records[i].tooltip) );
    28.     ...
    29.   }
    30.   ...
    31.  
    32. }
    And then we can modify MyEnum slightly
    Code (csharp):
    1. [Serializable]
    2. public class MyEnum : QuasiEnum, ISerializationCallbackReceiver {
    3.  
    4.   // this definition MUST be above the actual static readonly fields
    5.   static List<MyEnum> _enums = new List<MyEnum>();
    6.   static public MyEnum[] GetAll() => _enums.ToArray();
    7.  
    8.   static public MyEnum GetByName(string name) => GetByName<MyEnum>(name, _enums);
    9.   static public MyEnum GetByValue(int value) => GetByValue<MyEnum>(value, _enums);
    10.  
    11.   static public explicit operator MyEnum(int value) => GetByValue(value);
    12.  
    13.   static public readonly MyEnum zero = new MyEnum(0, "zero is naughty");
    14.   static public readonly MyEnum first = new MyEnum(1, "first is straight");
    15.   static public readonly MyEnum second = new MyEnum(2, "second is too late");
    16.   static public readonly MyEnum third = new MyEnum(3, "third is a charm");
    17.   static public readonly MyEnum fourth = new MyEnum(4, "fourth has quad damage");
    18.   static public readonly MyEnum fifth = new MyEnum(5, "fifth is a wheel");
    19.   static public readonly MyEnum sixth = new MyEnum(6, "sixth is a sense");
    20.   static public readonly MyEnum seventh = new MyEnum(7, "seventh is a seal");
    21.   static public readonly MyEnum eight = new MyEnum(8, "ate a pizza");
    22.   static public readonly MyEnum nine = new MyEnum(9, "nine is the captain of the bunch");
    23.   static private object _ = AutoGenerateNames<MyEnum>();
    24.  
    25.   [SerializeField] string @name; // must be called @name
    26.  
    27.   void ISerializationCallbackReceiver.OnBeforeSerialize()
    28.     => @name = this;
    29.  
    30.   void ISerializationCallbackReceiver.OnAfterDeserialize()
    31.     => ParseDeserialized<MyEnum>(@name, list: _enums, allowInvalid: true);
    32.  
    33.   string _description;
    34.  
    35.   private MyEnum(int value, string description) : base(value) {
    36.     _enums.Add(this);
    37.     _description = StringSanitizers.SimpleSanitizer.Process(description);
    38.   }
    39.  
    40.   public string DisplayName => _description;
    41.   public string TooltipString => $"Hint: {_description}";
    42.  
    43. }

    Feedback and questions are welcome.

    Edit:
    I've redacted the text above to reflect the latest version, where it mattered, and fixed some typos etc. The solution has changed dramatically in the meantime, however not by changing what was already explained, but by promoting the user class into yet another type-wrapper. This allowed me to do a second round of features, such as field auto-define. Then I decided to rename the whole thing to ErsatzEnumeration.

    You can download the latest version of ErsatzEnum (in source code) in post #12
     
    Last edited: Sep 21, 2022
  2. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,331
    Thanks for taking the time to share this! There's a bunch of useful functionality included here.

    One idea that comes to mind reading through this, is that the amount of boilerplate could be reduced even more (and some additional functionality baked in, such as implicit conversion operators) if a source generator was used.

    With this approach it could be possible to write just this:
    Code (CSharp):
    1. public sealed partial class MyEnum : QuasiEnum
    2. {
    3.     static public readonly MyEnum duck = 1;
    4.     static public readonly MyEnum beaver;
    5.     static public readonly MyEnum rabbit;
    6. }
    And then the rest of the functionality that can't be in the base class could be auto-generated in a second partial class.
    Code (CSharp):
    1. public partial class MyEnum
    2. #if UNITY_EDITOR
    3. : ISerializationCallbackReceiver
    4. #endif
    5. {
    6.     static public readonly MyEnum none = new MyEnum(nameof(none));
    7.  
    8.     private MyEnum(string name) : base(name) { }
    9.  
    10.     public static implicit operator int(MyEnum myEnum)
    11.     {
    12.         return myEnum?.name switch
    13.         {
    14.             nameof(none) => 0,
    15.             nameof(duck) => 1,
    16.             nameof(beaver) => 2,
    17.             nameof(rabbit) => 3,
    18.             _ => -1
    19.         };
    20.     }
    21.  
    22.     public static implicit operator string(MyEnum myEnum) => myEnum?.name;
    23.  
    24.     public static IEnumerable<MyEnum> All
    25.     {
    26.         get
    27.         {
    28.             yield return duck;
    29.             yield return beaver;
    30.             yield return rabbit;
    31.         }
    32.     }
    33.  
    34.     static MyEnum()
    35.     {
    36.         beaver = new MyEnum(nameof(beaver));
    37.         rabbit = new MyEnum(nameof(rabbit));
    38.     }
    39.  
    40.     public static implicit operator MyEnum(int value)
    41.     {
    42.         return value switch
    43.         {
    44.             0 => none ?? new MyEnum(nameof(none)),
    45.             1 => duck ?? new MyEnum(nameof(duck)),
    46.             2 => beaver ?? new MyEnum(nameof(beaver)),
    47.             3 => rabbit ?? new MyEnum(nameof(rabbit)),
    48.             _ => null
    49.         };
    50.     }
    51.  
    52.     public static implicit operator MyEnum(string name)
    53.     {
    54.         return name switch
    55.         {
    56.             nameof(none) => none ?? new MyEnum(nameof(none)),
    57.             nameof(duck) => duck ?? new MyEnum(nameof(duck)),
    58.             nameof(beaver) => beaver ?? new MyEnum(nameof(beaver)),
    59.             nameof(rabbit) => rabbit ?? new MyEnum(nameof(rabbit)),
    60.             _ => null
    61.         };
    62.     }
    63.  
    64.     #if UNITY_EDITOR
    65.     void ISerializationCallbackReceiver.OnBeforeSerialize()
    66.     {
    67.         switch(name)
    68.         {
    69.             case nameof(none):
    70.             case nameof(duck):
    71.             case nameof(beaver):
    72.             case nameof(rabbit):
    73.                 return;
    74.             default:
    75.                 Debug.LogError($"Invalid serialized MyEnum value detected: {name}.");
    76.                 return;
    77.         }
    78.     }
    79.  
    80.     void ISerializationCallbackReceiver.OnAfterDeserialize()
    81.     {
    82.         switch(name)
    83.         {
    84.             case nameof(none):
    85.             case nameof(duck):
    86.             case nameof(beaver):
    87.             case nameof(rabbit):
    88.                 return;
    89.             default:
    90.                 Debug.LogError($"Invalid serialized MyEnum value detected: {name}.");
    91.                 return;
    92.         }
    93.     }
    94.     #endif
    95. }

    Outside of this, it should also be possible to get rid of the need to manually assign names or values to the members (or call AutoGenerateNames) by using reflection to inject default values to fields that have a null value.

    Code (CSharp):
    1. #if UNITY_EDITOR
    2. [InitializeOnLoad]
    3. #endif
    4. [Serializable]
    5. public abstract class QuasiEnum
    6. {
    7.     [SerializeField]
    8.     private string name;
    9.     [SerializeField]
    10.     private int value;
    11.  
    12.     protected QuasiEnum() { } // removes the need to define a constructor in derived classes
    13.  
    14.     protected QuasiEnum(string name, int value)
    15.     {
    16.         this.name = name;
    17.         this.value = value;
    18.     }
    19.  
    20.     protected QuasiEnum(int value)
    21.     {
    22.         name = null;
    23.         this.value = value;
    24.     }
    25.  
    26.     [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    27.     private static void EnsureStaticConstructorIsExecuted() { }
    28.  
    29.     static QuasiEnum()
    30.     {
    31.         foreach(var type in GetDerivedTypes())
    32.         {
    33.             int nextUnderlyingValue = 0;
    34.  
    35.             var fields = GetPublicStaticFields(type);
    36.             HashSet<int> existingUnderlyingValues = new HashSet<int>();
    37.             foreach(var field in GetPublicStaticFields(type))
    38.             {
    39.                 if(field.GetValue(null) is QuasiEnum value)
    40.                 {
    41.                     existingUnderlyingValues.Add(value.value);
    42.                 }
    43.             }
    44.  
    45.             foreach(var field in GetPublicStaticFields(type))
    46.             {
    47.                 if(!typeof(QuasiEnum).IsAssignableFrom(field.FieldType))
    48.                 {
    49.                     continue;
    50.                 }
    51.  
    52.                 var value = field.GetValue(null) as QuasiEnum;
    53.                 bool isNull = value is null;
    54.                 bool isMissingName = !isNull && string.IsNullOrEmpty(value.name);
    55.  
    56.                 if(!isNull && !isMissingName)
    57.                 {
    58.                     continue;
    59.                 }
    60.  
    61.                 var setValue = FormatterServices.GetUninitializedObject(type);
    62.                 typeof(QuasiEnum).GetField(nameof(name), BindingFlags.NonPublic | BindingFlags.Instance).SetValue(setValue, field.Name);
    63.  
    64.                 if(isNull)
    65.                 {
    66.                     typeof(QuasiEnum).GetField(nameof(value), BindingFlags.NonPublic | BindingFlags.Instance).SetValue(setValue, nextUnderlyingValue);
    67.                     do
    68.                     {
    69.                         nextUnderlyingValue++;
    70.                     }
    71.                     while(!existingUnderlyingValues.Add(nextUnderlyingValue));
    72.                 }
    73.                 else
    74.                 {
    75.                     typeof(QuasiEnum).GetField(nameof(value), BindingFlags.NonPublic | BindingFlags.Instance).SetValue(setValue, field.GetValue(null));
    76.                 }
    77.            
    78.                 field.SetValue(null, setValue);
    79.             }
    80.         }
    81.  
    82.         static IEnumerable<Type> GetDerivedTypes()
    83.         {
    84.             foreach(var assembly in AppDomain.CurrentDomain.GetAssemblies())
    85.             {
    86.                 foreach(var type in assembly.GetTypes())
    87.                 {
    88.                     if(typeof(QuasiEnum).IsAssignableFrom(type) && type != typeof(QuasiEnum))
    89.                     {
    90.                          yield return type;
    91.                     }
    92.                 }
    93.             }
    94.         }
    95.  
    96.         static IEnumerable<FieldInfo> GetPublicStaticFields(Type type)
    97.         {
    98.             return type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
    99.         }
    100.     }
    101. }
    Usage:
    Code (CSharp):
    1. public sealed class MyEnum : QuasiEnum
    2. {
    3.     static public readonly MyEnum none;
    4.     static public readonly MyEnum duck;
    5.     static public readonly MyEnum beaver;
    6.     static public readonly MyEnum rabbit;
    7. }
    Test:
    Code (CSharp):
    1. [MenuItem("Test/Test MyEnum")]
    2. public static void Test()
    3. {
    4.     Debug.Log(MyEnum.none.name + " : " + MyEnum.none.value); // prints "none : 0"
    5.     Debug.Log(MyEnum.duck.name + " : " + MyEnum.duck.value); // prints "duck : 1"
    6.     Debug.Log(MyEnum.beaver.name + " : " + MyEnum.beaver.value); // prints "beaver : 2"
    7.     Debug.Log(MyEnum.rabbit.name + " : " + MyEnum.rabbit.value); // prints "rabbit : 3"
    8. }
     
    Last edited: Sep 16, 2022
    orionsyndrome likes this.
  3. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    Thanks for replying! That's definitely a different and interesting approach.

    I kind of don't really like or use generators, because in my experience they massacre the code base and transplant the programmer from the position of parsing it into some sort of abstract heavens, where things like race condition become a commonplace (you're more like a dispatcher, observing a never-ending train routing panel, where the train collisions are inevitable). I've been in a position of maintaining a code that was generated by some very expensive tool and was thoroughly disappointed with how little anybody understood the underlying system, and this produced a feedback loop on the system.

    And it's not that I believe the programmers should be exclusively crunching lines of code, but that the tools are typically so messy and obtuse to the point of actually sacrificing productivity and optimality of the solution. I.e. nobody is ever going to maintain the generated code (not even the generator which is just absurd) and this pretty much escalates into an effect similar to 'Phantom traffic jam' (aka traffic wave), where you get anomalous perturbances in the system without anyone being responsible.

    Ok that's the explanation why I don't go down this route, however, in this particular case, enums are pretty static anyway, and the extended functionality is pretty straightforward (and a 'leaf' in a code-base diagram, so to speak). So the questions are
    - what would be the cons of this kind of automation?
    - what would you use to auto-generate the code?
    - and would the standard enum be as pragmatic and ubiquitous if it came with a generator? (I mean arguably it already does, but I mean as a tool external to standard C# workflow.)

    Even though your initial class is super clean, there is a certain connotational burden.

    In my case, what you see is what you get, and I intend to lean it down further as much as I can, not so much so that it resembles the simplicity of your example -- I doubt that's achievable without some extra work like you've shown -- but so that it becomes harder to introduce an oversight or forget about the moving parts, both of which can cause fatigue in decision making.

    You know, I guess what I'm trying to say, what stops anyone from doing just "MyEnum > beaver, duck, possum" in a text file, and then run the automation suite? But this is not what solves the initial problem anymore. It has definitely lost the hands-on approach and the feelings of engagement and responsibility. I didn't even know how much I was weighing a machine-driven solution based on parameters that have nothing to do with the actual machines, so thanks for that.

    In fewer words, I guess what I'm delineating is "system" (state) vs "engineering" (process). I am not after the system per se. As I said "MyEnum > beaver, duck, possum" would be the best approach in the universe, because you then ultimately don't care about the implementation details at all.
     
    Last edited: Sep 17, 2022
  4. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,331
    Yeah, it's a valid concern that it can be more difficult to make alterations to code created by source generators (especially on a per-class basis).

    Maybe partially as a consequence of being an asset store dev, I tend to optimize heavily for the simplicity of the day-to-day developer experience, trying to remove as much friction as possible by pushing complexity down away from the most user-facing public APIs. But I hear you that on the flip side making things too simple can also serve to take people further away from what made them fall in love with programming in the first place :)

    This discussion reminds me of the record type a little bit; one could make the argument that it can help one write more elegant and expressive code, with less noise - but on the flip side the final C# code that gets generated is very ugly, and no simpler for the computer to execute in the end than if the developer had simply written that boilerplate themselves.
     
    orionsyndrome likes this.
  5. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    This is a very interesting discussion.

    I'm not talking about personal preferences or impressions here, though I do generally seem to people like an emotional type (I probably am). But it's not about me being attached to certain aspects of programming (even though I am), it's about the dichotomy between the craft and the industry, and this is a very intense anthropological subject.

    You see, if we talk about mining, for example, we can all differentiate between a miner and a mining operation. To exaggerate a bit, the miner can't do much and is more likely to get hurt at some point, while the mining operation is a shapeless endeavor that can disintegrate a mountain. But it's not without it costs, which can be enormous, not to mention the social and ecological footprint. So the crux of the issue is at which point in time should the miner become a mining operation? And is there an inflection point in this continuum?

    It turns out that all human endeavors suffer from this apparent linearity where some singular interest, activity, or motion is capable of insurrecting the whole of human race into a bustle which can only be described as "business" or "economy". Once that happens, the notion of management is inevitable. It is that surplus activity that perfectly delineates craft from an industry, along with the standardization.

    However, the economy of scale must not preclude the premature individual process, but since the individual process is constantly evolving, the inflection point becomes a question of strategy, to minimize the costs and streamline the management toward some measurable goal. I think this is why we "need" politics, basically. And I think at this point you can see where and why I draw the parallel between mining and programming.

    Likewise, a developed industrial capacity does not eliminate the need for perfecting the individual process. It actually depends on it. The nature of a problem doesn't magically go away once you encourage the whole country to do it (but it's harder for an individual to consider oneself as capable of introducing a change). And this is why we should never constrain ourselves by that which only a management would approve.

    In fact, I would go as far to claim that individually we should strive to do exactly the opposite, as this is the only way to increase the cost of the inertial systems that have already scaled wastefully. In that sense I firmly believe that auto-generated code not only does not help the individual, but increases the tech debt to the point where the individual is losing, and the establishment is "winning" (for a short while before the inevitable crash ensues due to interconnected feedback loops in every such economy of scale).

    I'm not sure if you (or anyone for that matter) can follow my philosophical tirades, but thanks for the involvement. Anyway, your example inspired me in a couple of surprising ways and this is what I have at the moment.

    Code (csharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. public class ErsatzEnumTest : MonoBehaviour {
    5.  
    6.   [SerializeField]
    7.   [ErsatzEnum(ErsatzEnumOptions.ShowValue | ErsatzEnumOptions.IncludeSelectableNone | ErsatzEnumOptions.UseTooltipString, ErsatzEnumSorting.ByValue)]
    8.   MyEnum[] _enum;
    9.  
    10.   [Serializable] private sealed class MyEnum : ErsatzEnum<MyEnum> {
    11.  
    12.     static public explicit operator MyEnum(int value) => GetByValue(value);
    13.  
    14.     //-----------------------------------------------------
    15.  
    16.     static public readonly MyEnum zero = new MyEnum(0, "zero is naughty");
    17.     static public readonly MyEnum first = new MyEnum(1, "first is straight");
    18.     static public readonly MyEnum second = new MyEnum(2, "second is too late");
    19.     static public readonly MyEnum third = new MyEnum(3, "third is a charm");
    20.     static public readonly MyEnum fourth = new MyEnum(4, "fourth has quad damage");
    21.     static public readonly MyEnum fifth = new MyEnum(5, "fifth is a wheel");
    22.     static public readonly MyEnum sixth = new MyEnum(6, "sixth is a sense");
    23.     static public readonly MyEnum seventh = new MyEnum(7, "seventh is a seal");
    24.     static public readonly MyEnum eight = new MyEnum(8, "ate a pizza");
    25.     static public readonly MyEnum nine = new MyEnum(9, "nine is the captain of the bunch");
    26.  
    27.     //-----------------------------------------------------
    28.  
    29.     static MyEnum() => ErsatzEnum<MyEnum>.DeserializationSettings(allowNone: true);
    30.  
    31.     string _desc;
    32.  
    33.     private MyEnum(int value, string desc) : base(value) {
    34.       _desc = StringSanitizers.SimpleSanitizer.Process(desc);
    35.     }
    36.  
    37.     //-----------------------------------------------------
    38.  
    39.     public string DisplayName => _desc;
    40.     public string TooltipString => $"Hint: {_desc}";
    41.  
    42.   }
    43.  
    44. }
    The solution was to introduce an intermediate class that is aware of the user-type. I've also cleaned up the project thoroughly and renamed it to ErsatzEnum. Still working on it but I think it's beautiful. As soon as I stress test this a little more, I will dump the full code and update the guide above.

    This is the intermediate class
    Code (csharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [Serializable]
    6. public abstract class ErsatzEnum<T> : ErsatzEnumCore, ISerializationCallbackReceiver where T : ErsatzEnumCore {
    7.  
    8.   static List<T> _list = new List<T>();
    9.  
    10.   static public T[] GetAll() => _list.ToArray();
    11.  
    12.   static public T GetByName(string name)
    13.     => GetByName<T>(name, _list);
    14.  
    15.   static public T GetByValue(int value)
    16.     => GetByValue<T>(value, _list);
    17.  
    18.   static object _ = AutoGenerateNames<T>();
    19.  
    20.   static bool _allowNone, _allowInvalid, _suppressLog;
    21.  
    22.   static public void DeserializationSettings(bool allowNone = true, bool allowInvalid = false, bool suppressLog = false)
    23.     => (_allowNone, _allowInvalid, _suppressLog) = (allowNone, allowInvalid, suppressLog);
    24.  
    25.   [SerializeField] string name;
    26.  
    27.   void ISerializationCallbackReceiver.OnBeforeSerialize()
    28.     => name = this;
    29.  
    30.   void ISerializationCallbackReceiver.OnAfterDeserialize()
    31.     => ParseDeserialized<T>(name, list: _list, _allowNone, _allowInvalid, _suppressLog);
    32.  
    33.   protected ErsatzEnum(int value) : base(value)
    34.     => _list.Add(this as T);
    35.  
    36. }
     
    SisusCo likes this.
  6. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,331
    Glad to hear you were perhaps able to extract some value from my wandering throughs!

    I think I get you. Cost–benefit analysis, premature optimization, overengineering, technical debt, KISS, YAGNI. And re-traumatization avoidance :p
     
    orionsyndrome likes this.
  7. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    when paradigms are agile patterns are solid
     
  8. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    I am proud to report that this now works
    Code (csharp):
    1. [Serializable]
    2. class MyEnum : ErsatzEnum<MyEnum> {
    3.  
    4.   static public readonly MyEnum duck;
    5.   static public readonly MyEnum rabbit;
    6.   static public readonly MyEnum beaver;
    7.   static public readonly MyEnum _porcupine;
    8.  
    9.   private MyEnum(string name, int value) : base(name, value) {}
    10.  
    11. }
    This produces the following drop-down
    Code (csharp):
    1. Duck (0)
    2. Rabbit (1)
    3. Beaver (2)
    4. Porcupine (3)
    You can still override each element individually, and decorate it with tooltips and custom display names.
    Adding a defined element to an undefined list, will auto-increment the values, much like standard enum.

    This
    Code (csharp):
    1. [Serializable]
    2. class MyEnum : ErsatzEnum<MyEnum> {
    3.  
    4.   static public readonly MyEnum duck;
    5.   static public readonly MyEnum rabbit;
    6.   static public readonly MyEnum beaver;
    7.   static public readonly MyEnum possum = new MyEnum(8);
    8.   static public readonly MyEnum _porcupine;
    9.  
    10.   private MyEnum(int value) : base(value) {}
    11.   private MyEnum(string name, int value) : base(name, value) {}
    12.  
    13. }
    produces
    Code (csharp):
    1. Duck (0)
    2. Rabbit (1)
    3. Beaver (2)
    4. Possum (8)
    5. Porcupine (9)
    However, all fields are serialized as strings so there is no headache when adding or removing.
    This is an excerpt from the scene YAML (serialized array)
    Code (csharp):
    1. _enum:
    2. - name: rabbit
    3. - name: beaver
    4. - name: '*'
    5. - name: _porcupine
    '*' is now a special signal when the drawer is allowed to produce 'None' as a pseudo-identity.

    The system will also analyze the fields and notice a missing 'readonly' (or a wrong type) and I'm currently working on registering duplicates (which can happen when the names are all manually set). The names can be decoupled from the in-code field names (if that's desirable) and the automatic name generation is still in place if a name is set to empty ("") on purpose.

    All that's left is to make an attribute for the class itself, because there are 5 different settings now:
    - auto-define (on start)
    - auto-name (on start)
    - allow none (when deserializing)
    - allow invalid (when deserializing)
    - suppress log (when invalid)

    Right now I'm pulling them at the right moment, which is before assembly gets fully initialized, and because I have zero control over this I don't get to choose the aesthetics of this solution, so it's just a brick-looking method with five flags that you have to write if you want to change something. And I'm thinking the attribute will be more elegant, and at disposal.

    The only caveat I've discovered so far is that it mustn't have a parameterless constructor. This, for some reason, demolishes the entire system. It's very weird. I'm guessing it's serialization, but who knows.
     
  9. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,331
    Awesome job! :cool: Glad to see that you were able to get rid of the need to call AutoGenerateNames. This looks super user-friendly now.

    The reason why adding a protected parameterless constructor to the base class beaks everything is that Activator.CreateInstance (I'm assuming that is what you're using) can no longer find a constructor to invoke with reflection in the derived classes, because constructors aren't inherited from base classes. FormatterServices.GetUninitializedObject can be used to create an instance instead, and then field, property or method injection can be used to initialize it.
     
    orionsyndrome likes this.
  10. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    Indeed, that's what I thought as well! But then after a series of experiments I concluded it was a relative mystery because just a mere existence of a parameterless c-tor would break everything even if I didn't use it (i.e. if I remove reflection calls completely). Anyway I switched to InvokeMember instead of CreateInstance. Thanks for the tip, I'll check out GetUninitializedObject pronto.

    The main issue with this was how to access the protected c-tor from the base class (it sounds wrong anyway, but really made sense in this case). But if I can inject a method, that's even better.

    Now the attribute is on the class itself. I reuse the settings both in the initialization and for the drawer.
     
    SisusCo likes this.
  11. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    hahaha GetUninitializedObject worked perfectly.
    So perfectly in fact that it completely circumvented the intended c-tor behavior :)
    Namely the internal list registration, I forgot about that quirk, so annoying.

    Anyway this has prompted me to find a way around it, and I've discovered that the base class can't see a protected member of its subclass (the type of which it knows, and its base type is itself). I probably just can wrap my head around it, but it sounds so stupid on paper.

    In any case I moved away from that solution entirely, and changed the way I'm registering the entries altogether, because I had to ensure (manual) names weren't duplicated regardless (especially when mixed with auto-define). And now you don't even need to have a default c-tor in the user class for all of this to work. Thanks for that, that part was really bothering me.

    Here's an example
    Code (csharp):
    1. [ErsatzEnum(ErsatzEnumSetting.AutoDefineFields)]
    2. [Serializable] class MyEnum : ErsatzEnum<MyEnum> {
    3.  
    4.   static public readonly MyEnum duck;
    5.   static public readonly MyEnum rabbit;
    6.   static public readonly MyEnum beaver;
    7.   static public readonly MyEnum possum = new MyEnum(5);
    8.   static public readonly MyEnum _porcupine;
    9.  
    10.   private MyEnum(int value) : base(value) {}
    11.  
    12. }
     
    SisusCo likes this.
  12. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    The source can be downloaded from here (v1.0).
    (I'm not a GitHub user and the source code is just zipped for convenience.)

    It consists of five files:
    • Attributes/ErsatzEnumAttribute.cs (doesn't work on the serialized field anymore)
    • Editor/ErsatzEnumDrawer.cs (QuasiEnumDrawer but overhauled)
    • ErsatzEnum.cs (introduced as a type-wrapper class)
    • ErsatzEnumCore.cs (what used to be called QuasiEnum, but expanded)
    • StringSanitizers.cs (as shown in the guide)
    Usage should be pretty self-explanatory (with the snippets scattered all over this thread), and if not I'll make sure to add more examples.

    Because it's too early to tell, the thing might contain bugs.
    If anyone encounters any bugs or weird behavior, tell me here.
    There is one known issue: User class must not contain a constructor without parameters.
    That would be this code
    Code (csharp):
    1. private MyEnum() : base("", 0) {} // no arguments = malfunction
    Features I've covered so far:
    - validation of public static fields (must be readonly for example)
    - name duplication check (when you set your names manually)
    - automatic name definition and auto-incrementing integer values (when AutoDefine is on)
    - back-stage auto-filling when names are deliberately set to empty strings ("")
    - fully operational custom drawer for Unity inspectors (you can make custom editors with it)
    - support for custom display names and tooltips as well as basic string sanitation
    - serialization by name, not by value, allowing you to freely add or remove entries without corrupting everything
    - allowing for 'None' values in drawer (and some output customization, like sorting)
    - handling issues with deserialization
    - public domain do-whatever-you-want license

    The attribute in this version is used on the class itself, not on your serialized variable.

    Here's one example use scenario for when you do allow for 'None' as a state identity.
    Code (csharp):
    1. [ErsatzEnum(ErsatzEnumOptions.DisplayAndTooltip | ErsatzEnumOptions.IncludeSelectableNone,
    2.             ErsatzEnumSorting.ByValue, ErsatzEnumSetting.AllowNone)]
    3.  
    4. [Serializable] public class MyEnum : ErsatzEnum<MyEnum> {
    5.  
    6.   // this allows you to check for this special case throughout your code
    7.   static public bool IsNone(MyEnum @enum) => ErsatzEnum<MyEnum>.IsNone(@enum);
    8.  
    9.   // this allows you to cast your custom enums to values in a typical manner, i.e. (MyEnum)8
    10.   static public explicit operator MyEnum(int value) => GetByValue(value);
    11.   // this will return null if the value does not exist, and will return only the first enum if multiple were found
    12.  
    13.   // the other way around works by virtue of the core class, i.e. (int)MyEnum.fifth
    14.   // trying to extract a value from an undefined enum will result in a crash, for safety
    15.   // trying to extract a string from an undefined enum will return 'null'
    16.  
    17.   // because we set these values these fields do not count as "undefined"
    18.   // and will simply auto-fill their names
    19.   static public readonly MyEnum zero = new MyEnum(0, "zero is naughty");
    20.   static public readonly MyEnum first = new MyEnum(1, "first is straight");
    21.   static public readonly MyEnum fourth = new MyEnum(4, "fourth has quad damage");
    22.   static public readonly MyEnum third = new MyEnum(3, "third is a charm");
    23.   static public readonly MyEnum second = new MyEnum(2, "second is too late");
    24.   static public readonly MyEnum fifth = new MyEnum(5, "fifth is a wheel");
    25.   static public readonly MyEnum sixth = new MyEnum(6, "sixth is a sense");
    26.   static public readonly MyEnum seventh = new MyEnum(7, "seventh is a seal");
    27.   static public readonly MyEnum eighth = new MyEnum(8, "ate a pizza");
    28.   static public readonly MyEnum ninth = new MyEnum(9, "nine is the captain of the bunch");
    29.  
    30.   // You must avoid parameterless constructor as it will break everything!
    31.  
    32.   string _desc;
    33.  
    34.   // Example of a user-set constructor: just a value and custom arg
    35.   private MyEnum(int value, string desc) : base(value) // the name is internally set as ""
    36.     => _desc = StringSanitizers.SimpleSanitizer.Process(desc).Trim();
    37.  
    38.   // custom display name and tooltip
    39.   public string DisplayName => _desc;
    40.   public string TooltipString => $"Tooltip: {_desc}";
    41.  
    42. }
    All names are case-insensitive.
    Do your naming according to your standards, the above code is just a test example.

    Check out the previous (edit: or next) comment for another usage example with undefined fields.
     
    Last edited: Sep 19, 2022
  13. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    Another example with AutoDefine and 'None'
    Code (csharp):
    1. using System;
    2. using UnityEngine;
    3. using ErsatzEnumeration;
    4.  
    5. // this is so we can access the fields in this test
    6. // without having to begin with MyEnum. all the time
    7. // completely non-mandatory
    8. using static ErsatzEnumTest.MyEnum;
    9.  
    10. // same thing for Debug
    11. using static UnityEngine.Debug;
    12.  
    13. [ExecuteInEditMode]
    14. public class ErsatzEnumTest : MonoBehaviour {
    15.  
    16.   [SerializeField] MyEnum _single;
    17.   [SerializeField] MyEnum[] _array;
    18.  
    19.   void OnValidate() {
    20.     Log($"duck {duck}"); // duck
    21.     Log($"rabbit.Value {rabbit.Value}"); // 1
    22.     Log($"(int)possum {(int)possum}"); // 5
    23.     Log($"(int)(MyEnum)_porcupine.Name {(int)(MyEnum)_porcupine.Name}"); // 6
    24.     Log($"value of {(MyEnum)2} is {((MyEnum)2).Value}"); // value of beaver is 2
    25.     //Log($"value of {(MyEnum)3} is {((MyEnum)3).Value}"); // would produce an error
    26.     Log($@"(MyEnum)""duck"" {(MyEnum)"duck"}"); // duck
    27.     Log($@"(MyEnum)""giraffe"" == null {(MyEnum)"giraffe" == null}"); // True
    28.     Log(possum != beaver); // True
    29.     Log(possum == possum); // True (also produces a compiler warning)
    30.     Log(possum.CompareTo(_porcupine)); // -1
    31.     Log("---");
    32.     Log($"_single == rabbit {_single == rabbit}");
    33.     Log($"_single.IsNone() {_single.IsNone()}");
    34.     if(_array.Length >= 2) Log($"_array[1] {_array[1]}");
    35.     if(_array.Length >= 3) Log($@"(string)_array[2]+""!"" {(string)_array[2]+"!"}");
    36.     if(_array.Length >= 3) Log($"_array[2].AsValidOr(duck) {_array[2].AsValidOr(duck)}");
    37.   }
    38.  
    39.   [ErsatzEnum(ErsatzEnumOptions.IncludeSelectableNone,
    40.      ErsatzEnumSorting.ByName, ErsatzEnumSetting.AutoDefineFields | ErsatzEnumSetting.AllowNone)]
    41.  
    42.   [Serializable] public sealed class MyEnum : ErsatzEnum<MyEnum> {
    43.  
    44.     // i.e. _single.IsNone()
    45.     public bool IsNone() => ErsatzEnum<MyEnum>.IsNone(this);
    46.  
    47.     // as a convenience when handling None-friendly enums
    48.     public MyEnum AsValidOr(MyEnum dflt) => this.IsNone()? dflt : this;
    49.  
    50.     // optional static test (so you can also MyEnum.IsNone(_single))
    51.     static bool IsNone(MyEnum en) => ErsatzEnum<MyEnum>.IsNone(en);
    52.  
    53.     static public explicit operator MyEnum(string name) => GetByName(name);
    54.     static public explicit operator MyEnum(int value) => GetByValue(value);
    55.  
    56.     static public readonly MyEnum duck; // implicitly 0
    57.     static public readonly MyEnum rabbit; // implicitly 1
    58.     static public readonly MyEnum beaver; // implicitly 2
    59.     static public readonly MyEnum possum = new MyEnum(5); // explicitly 5
    60.     static public readonly MyEnum _porcupine; // implicitly 6
    61.  
    62.     private MyEnum(int value) : base(value) {}
    63.  
    64.   }
    65. }
     
    Last edited: Sep 19, 2022
    SisusCo likes this.
  14. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    I went through the tut once again, fixed some typos etc.
    Also wanted to say thanks to @SisusCo . The solution turned out great thanks to his input.

    If you want enums that serialize as strings, here's a minimal use case example (if the more complicated ones scare you away).
    Code (csharp):
    1. using ErsatzEnumeration;
    2.  
    3. [ErsatzEnum(ErsatzEnumSetting.AutoDefineFields)]
    4. public sealed class MyEnum : ErsatzEnum<MyEnum> {
    5.  
    6.   static public readonly MyEnum DireBear;
    7.   static public readonly MyEnum WereWolf;
    8.   static public readonly MyEnum IRSTroll;
    9.   static public readonly MyEnum VagabondHobbit;
    10.  
    11. }
    Download button is two posts above.
     
  15. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,331
    You got it, I'm glad I was of some help :)
     
    orionsyndrome likes this.
  16. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    Btw does anyone has ANY idea how to find an index of a serialized array differently?
    (And for that matter how to manage the serialized array properly, but that's probably a wider topic.)

    I've included two methods in my solution, because even though the first one is relatively proper, it is O(n), which mandates the other method, one that slices the actual property path (and parses to int), and that seems to be the only source of this information. It's not that this method is slow, but I HATE IT.
    Code (csharp):
    1. // p is the leaf node i.e. "parent.someProperty.Array.data[2]"
    2. // arrayProperty is the actual "parent.someProperty", isolated in an earlier step
    3. int getArrayPropertyIndex(SerializedProperty p, SerializedProperty arrayProperty) {
    4.   if(arrayProperty is null) return -1;
    5.   if(arrayProperty.arraySize < 16) { // method #1 for small arrays
    6.     for(int i = 0; i < arrayProperty.arraySize; i++)
    7.       if(SerializedProperty.EqualContents(arrayProperty.GetArrayElementAtIndex(i), p))
    8.         return i;
    9.   } else { // method #2 for big arrays
    10.     var path = p.propertyPath;
    11.     var part = path.LastIndexOf('[') + 1;
    12.     return int.Parse(path.Substring(part, path.Length - part - 1));
    13.   }
    14.   return -1;
    15. }
    Both me and the rest of the world would be very grateful if there is a better solution (I don't mind if it's reflection-based). Apparently nobody at Unity thinks such a core serialization API thing should be exposed for the last 10 years or so.
     
    Last edited: Sep 24, 2022