Unity Dev Blog: Switch Statements in Unity vs If & Else If

Sometimes you just have to pick one.

In the last article I demonstrated how to implement multiple different types of power-ups using a single script. We assigned the power-ups unique numeric IDs and used that ID to determine what powers to give to the player.

Today, I am going to demonstrate how to use C#’s Switch statement to make the code more efficient and readable.

Here is the original code:

By replacing all of the IF-THEN statements with SWITCH/CASE logic, the code is more readable and we can still add in as many power-ups as we would like.

This may not seem like a big change and you might feel the original code was readable enough, and I would normally agree. But what if we had 100 different objects to test for? Those IF-THEN statements would take time to process and check.

The switch statement would know exactly which line to run next. After running that case the break key word tells Unity we did what we needed to do and it can exit the switch routine. Much more efficient than testing lots of IF-THENs.

So what’s next? The game is coming along nicely so I think it time for some UI, or user interface, elements to make it look even better. Don’t worry however, the explosion animations are coming soon. 😁

Tomorrow I will begin working on the user interface and discuss creating UI elements in Unity.

See you there!

--

--

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
Michael Hatfield

Michael Hatfield

Math and science teacher / self-taught programmer and Unity game developer working hard to get into the game development industry fulltime.