This content originally appeared on Level Up Coding - Medium and was authored by Jared Amlin

In my last article, I made a modular powerup system so that all of my powerups can share one script. I accomplished this task by assigning each powerup to an ID number, then running a series of if-else statements to check for the ID number on the power up when a collision occurs. Each different ID number will send a different message to the player script when its respective powerup is collected by the player. This is where I left off.


With only a few powerups, this really isn’t too bad. Can you imagine how this series of if-else checks would look if I had fifty powerups? That sounds like a long winded mess.
Converting these if-else statements to a switch statement will really clean up my script, and make it easier to add new powerups later in the development stage. I first open up a basic switch statement referencing the powerup ID variable.

In switch statements, you use something called a case, and cases need the keyword break between them. The case also needs a number to reference regarding the powerup it is representing, so I begin at zero for my triple shot. between my case and break keywords, I can send a message to the player to activate the triple shot, just like in an if-else statement.

Switch statements also take a default case, which will trigger if the player receives a powerup with an ID outside of the designated range. In this case that would be an error, so I chose to send a Debug.LogError message to the console to let me know that something unexpected has been triggered on a powerup collision.

I can now add in case one and two for my speed boost and shield powerups. I don’t yet have methods for these messages set up on my player script yet, but I can still test the connection by sending some debug messages.

I implemented some logic on my player script for the speed and shield powerups that I will cover in my next couple of articles. For the sake of staying on the topic of switch statements, I will jump right back to my powerup script below.
Now that my player script is all ready for input from the powerup script, I can change the debug lines in my switch statement in my powerup script to activate the proper methods.

Everything is essentially working as it was before, only with a cleaner and more streamlined design that will help me as I bring more powerups into the game.
Clean Up That Code with Switch Statements was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Jared Amlin

Jared Amlin | Sciencx (2021-05-25T12:52:04+00:00) Clean Up That Code with Switch Statements. Retrieved from https://www.scien.cx/2021/05/25/clean-up-that-code-with-switch-statements/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.