Switch statements and Enums!

Switch statements are very convenient when you want to compare a single nonstatic variable to determine which course of action should be taken. They act similarly to chained if-else statements but tend to be regarded as something a bit more cleaner and better performance-wise.

Let’s take a look at the if statements and how you would handle different values of your variable. Your code would end up looking something like this:

This does look a little bit chaotic, and the more if-else statements you add, the less performant your code will be!

So what can be done about this, especially if you have three or more of these statements? - Well, either you can get down to refactoring your code, making it less dependant on all of the if-else statements, which can get a bit more advanced… or you can “switch” it!

What is a Switch statement?

Similar to an if-else statement, the switch is a conditional statement. It directs the flow of code to one of a number of possible code blocks.

  • Every switch statement must start with the keyword ‘switch()’ - you then place a variable of a particular type. A switch works with the byte, short, char, and int primitive data types. But it also works with enumerated types( read about them lower!)
  • ‘Case’ defines the individual block of code that runs when the variable's value matches the one in the case.
  • Each ‘case’ must end with a ‘break;’ command, which indicates the end of each case.
  • You can also use a ‘default’ case, which is called when the variable's value does not match any other case values.

Enumeration Type:

Switch statements can also be used with enumeration types ( short for ‘enum’). It is a value type defined by a collection of named constants, each of them with a specific number value, integer by default.

  • To create an enum, define the accessibility level, use the ‘enum’ keyword, followed by its name.
  • The enum values start at 0, counting up with each enum item. But you can also set the value of an object manually.

We can now adjust our code in our ‘PowerUp’ script a little bit!

As we can see, the benefit is obvious - the meaning of the code is evident right away, without having to scroll through each object and finding out which ‘Id’ they have set.

When we hop back into the Unity and look at each of our powerup Prefab in the ‘Inspector,’ we can assign each of them with a specific enum value right away! You also can’t make the mistake of selecting a value outside of the ‘switch’ range.

But that is it for now, thank you for reading and feel free to follow me for more articles - and as always, good luck and see you next time!

Aspiring and eager beginner Unity developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store