Switch Statements in Unity

Stephen York
2 min readMar 24, 2021

Else if statements are great. They allow you to easily execute logic based on different values of a parameter.

But the problem is that if you are using quite a few of them, your code starts to look cluttered. And that’s the beauty of switch statements: they basically function the same way as else if statements, but they look cleaner. A good general practice is that if you are using more than two else if statements, use a switch statement instead.

But let’s walk through an example. We are going to transition the above else if statement into a switch statement. Now, that else if statement doesn’t look bad, but if you had 20 powerups, that’s 17 more

But the switch statement will just run through a series of cases based on the input. To start, type switch(id) and the id are the cases that we will be considering, just like when we were checking if id equaled some integer in the if statement. Then you run through the cases you want to consider (for this example, 0, 1, and 2). For each case, you write the logic you want to happen if that case is true, and then you end it with the keyword “break;” which signifies that the current case is over and will allow you to start the next case.

And at the end is the “default” case which will run if none of the other cases are satisfied.

Both ways, the else if and the switch, will give the same results but the switch looks cleaner when there are many cases to consider.

--

--

Stephen York

An Atlanta based Unity developer, who enjoys running, reading, and creating videogames!