Mind Enuming: Enums in Unity
Have you ever wished you could just use some standard language to represent your values? Well now you can with Enums. In C# these are primitive data types using regular language to represent a constant. They’re basically ints with added checks. So how do you use one, well it’s initialized the same way as a class like below with each enum seperated by a comma.
You can also use them within classes but typically they sit outside an existing class so that they can be used wherever they are needed. Additionally you can also assign specific values to each enum since they are basically ints. If left unassigned them increment by 1 starting at 0.
‘
A good example of a use case for an enum would be a difficulty setting. In the example below we have 3 game difficulties that we can assign through a switch statement.
As we illustrate above this makes it very easy to make readable states to make it far more clearer than using standard ints to switch between them. Which can be a little opaque to a designer (or even yourself a few months later) to parse at a glance. A nice feature is that even print to a string like below.
Lastly we can cast enums as ints, this is super helpful if we need to get a particular value of the enum. For example if we have the enums represent multipliers (2, 4, 8, 10x etc.) we can get those values as ints by explicitly casting them. Down below we can see that in action.
Here we set the previous difficulty levels we created to their corresponding score multiplier.
Then we print out the multiplier by casting difficultyLevel with an int in parentheses. This is our final result.
Enums are a handy tool in your programmatic toolkit, they can provide you with legible easy to understand values. You can use them to do many things a string or int would allow in one neat package. Their ease makes them popular with AI for states but can be adapted to mark pickups, enemy types, change game states, or even change levels using the Scene Manager. Your imagination is the only real limiter, until next time happy coding.