How to use Enum Flags in Unity C#

Dusk Sharp
5 min readMay 1, 2023

Create sets of related flags and get rid of all the Boolean checks!

Learn to use Enum Flags and enhance your Unity games!

Introduction

As a developer most people are aware of enums. An Enum is a special type of class that is used to assign constant names to groups of numeric integers. Instead of booleans for “canMove”, “hasItem” etc, you can represent the state of an object in a more descriptive way.

However sometimes you may need to allow for more than one enum to be active at a time. This can be done using Enum Flags. Enum flags are a specific type of enum in C# that can be used to represent sets of related boolean values. In Unity, you can see this used in places such as Shader channels, blocking masks, and other internal properties. In this article, we will discuss how to use enum flags in Unity C#.

Enums are defined in many places in Unity, and allows for these handy checkmark dropdowns!

Creating an Enum Flag

Let’s get started with creating an Enum Flag. Then we will show an example in practice.

To define an enum flag, you start by defining an enum type using the enum keyword, like you would with a standard enum. The enum keyword is followed by the name of the enum type and the values that it can take. Each value is separated by a comma.

There are a couple of differentiating factors. The [Flags] attribute is important to denote that it is used to define flags. And, the values that are supplied need to be compatible with bitwise operations. Here is one example.

[Flags]
public enum MyEnumFlag
{
None = 0,
Value1 = 1,
Value2 = 2,
Value3 = 4,
Value4 = 8
}

Once again, the [Flags] attribute is used to tell the compiler that this enum type is intended to be used as a bit field or flag. What is not as well known, however, is that you don’t need to specify the values in ascending order. By default, the values of the enum are assigned sequential integers, starting from 0. But, you can specify specific integer values for each enum value if necessary. In thise case we are following base 2.

Using Enum Flags

--

--