Unity Dev: Switch Statements in Unity

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!

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Home Assistant in Docker: The Ultimate Setup!

READ/DOWNLOAD![ Engineering Ethics: Concepts and C

Weekly essay — Open Source Round 1: Read other people’s code

Version Control — GitHub

Advent of CTF (December 2020)

Combining algorithmically generated art with a GAN

Functional Programing illustrated in Python: Part 1

ROOTCON 15 CTF Writeup — OSINT

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.

More from Medium

Bug Fix on Model Flip

How to Use Post Processing in Unity

Benefits of Prototyping without Assets

I think you dropped something — Creating a simple loot drop system in Unity2D