MyBox icon indicating copy to clipboard operation
MyBox copied to clipboard

Convert Enums to Flags directly

Open Nom-ali opened this issue 1 year ago • 2 comments

Is it possible that when i initialize an enum, If i could add something Like Flags, and convert this enum to Flags directly .

Example:

[MyBox.Flags]
[SerializeField] SharedEnums.DefaultEvents defaultEvents = SharedEnums.DefaultEvents.None;

public static class SharedEnums
{
   [System.Serializable]
   public enum DefaultEvents
   {
       None,
       OnEnable,
       OnDisable,
       OnDestroy,
   }

}

Nom-ali avatar Sep 13 '24 12:09 Nom-ali

It should be not possible, because when you declare an enum type, by default and under the hood underlying type of the enum is int and every item in the enum is assighed with integer. For this example – [None = 0, OnEnable = 1, OnDisable = 2, OnDestroy = 3]. When you adding [Flags] attribute to the enum you let the compiler know that integer layout should allow to store several values at a time. This way by default the layout will be [None == 0, OnEnable = 1, OnDisable = 2, OnDestroy= 4 (next would be 8, 16 etc)]. I'm simplifying things a bit, but with this case if variable "defaultEvents" assigned with value "3" the compiler could interpret it as a combination of OnEnable and OnDisable.

Well, as I'm writing this some ideas arising. It wouldn't be possible to directly use DefaultEvents as flags enum in the inspector and have adequate results, but it is possible to create some wrapper type to store a collection of enum values simply to emulate flags functionality in the inspector...

Why to bother though? You do not have the access to the DefaultEvents enum sources?

Deadcows avatar Sep 13 '24 19:09 Deadcows

There are some cases, Sometimes, I'm using same enum as Flag, I just don't want to create a separate enum for flags. Use a single enum for Enums and Flags.

Nom-ali avatar Sep 18 '24 05:09 Nom-ali