

If the first bit is one, it is a melee attack if the second bit is one, it is a fire attack, if the third bit is one it is an ice attack, and so on. As you can see below, this means that every non-zero label has exactly one 1 in its binary representation, and that they are all in different positions:Īt this stage, the variable attackType can be seen as a series of bits, each one indicating if it has or not a certain property. If we want to use at its best, we should use only powers of two for the values of our labels. Enums are store as integers when you have consecutive numbers, their bit representations look like this: But first we need to understand how this is actually working. We’ll see later how it is possible to retrieve these values. In the example above, attackType both holds Melee and Fire values. Public AttackType attackType = AttackType.Melee | AttackType.Fire This allows them to be treated as bit masks, storing multiple values between them: What if we are using a melee weapon with a fire attack (a fire sword?!)? To solve this problem, enums can be decorated with. The first limitation is that standard enums can only hold a value at a time. The vast majority of developers use enums just as we’ve seen before. There’s much more we can do with them though. If a public field is an enum, it will conveniently appear like a dropdown menu:

What makes enums even so interesting is the fact that they are automatically integrated in the Unity inspector. None is zero, Melee is one, Fire is two and so on. You can change that by explicitly changing the value of a label:Ĭasting an enum to int will return its integer value. Enums starts from zero and every new label is assigned the next integer number. Internally, every label has an integer value. These values are given symbolic labels for clarity and are also returned as string when needed:ĭebug.Log("Attack: " + attackType) # Prints "Attack: Poison" The definition of an enum creates a type which can support only a limited range or values. Public AttackType attackType = AttackType.None Luckily, C# has a construct called enum (for enumeration) which has been specifically designed for these situations:
