Level Up Your Unity Skills: Switch Statements to the Rescue

Gerald "Ray" Patton
2 min readMar 25, 2024

--

Objective: Clean up the Powerup Script “else-if” clause statements with more optimized “Switch” statements.

To begin this optimization I first had to take another look at my Powerup Script and the “else-if” clauses. What I found was a lot of clutter within the code:

As I looked at my code, I realized just how clunky and hard to read multiple “else-if” statements can be. When more than 1(one) “else-if” statements would have to be used, I can instead clean up the code by using the more advanced and improved “Switch” statement, to handle these same checks.

Instead of using “else-if”, “switch” uses what is called a “case”. Each “case” is used for every outcome that needs to be checked.

A lot red swiggles, Why?

When coding a “case”, I needed to attach a “break;” after each “case”, so the code knows when to end. If I have to try passing a “case” that is not being checked, I had also included a “default” value.

After completing my “switch” coding, I removed the old “else-if” statements, added my Power up prefabs to the scene, and tested the game one more time:

Notice the “Collected Speed Boost” message on the bottom.

Everything is working just as it did with the “else-if” statements, but much less cluttered. Our next step will be to write code to implement our Speed boost behaviour and random spawning. Until next time, Happy Developing!

--

--

Gerald "Ray" Patton

Unity Developer | C# Software Engineer | Game Developer | USAF Veteran