What's the best way to implement a "set" data Type in C#?

Hi Unity Answers Community,

I was wondering, (may be answered before but couldn’t find the answer), is there a “set” data type in Unity’s C#?

That is, an enum which elements could be present or not in a single time (e.g: in a game, the enemy’s immunities: fire, water and death)

something that could be easily implementable in the Inspector, much like the Culling mask of a Camera.

I was dreaming of a syntax like:

public set ImmunitiesSet of {
Fire,
Ice,
Holy
}

that automagically shows up properly in the inspector and allows Mask-like operations.

Since I’m pretty sure there isn’t a native solution, in your experience what’s the most straightforward way to implement this, in the most general case?

Thanks for your time.

Sure, you can use enums as bitmask, however you’re limited to 32 values of course. Also you should use hex numbers to specify the bitmask values, it’s less error prone :wink:

public enum SomeBitMask
{
    Value1  = 0x0001,
    Value2  = 0x0002,
    Value3  = 0x0004,
    Value4  = 0x0008,
    Value5  = 0x0010,
    Value6  = 0x0020,
    Value7  = 0x0040,
    // ...
}

To display a bitmask dropdown list in the inspector you can use this property drawer i’ve written.

Depending on the use case you could use a bit field, combining emum values together, but it’s not particularly well-supported by the language.

It is far clearer to just use a class containing a few public bool members.

public class Immunities
{
    public bool Fire;
    public bool Ice;
    public bool Holly;
}

Then you can add an Immunities field to your components and check the boxes in the Inspector, and the syntax for checking them from code is straightforward and readable.