Using switch statement and making speed powerup

Our last and third powerup we have is speed. We also see how we can effectively use our powerups and know which one we pickup

Photo by Blake Connally on Unsplash

Speed Powerup

I wanna write about the third powerup which I have in the Space Shooter 2D and that is SPEED. I think it tells us what we need.
After we pick up the powerup, our speed increases a specific amount and for a specific time.

The way we make this is the same as the triple shot powerup, if you haven’t read that article, you can find it here! Go check it out! :)

We need one thing different from the triple shot and that is that we multiply our _speed by _speedMultiplier.

We set our _speedBoostEnabled to true
Then multiply our _speed by our _speedMultiplier
Then we start a Coroutine (which is shown below)

After starting the Coroutine we wait for 5 seconds, then we set our _speedBoostEnabled to false and divide our _speed by _speedMultiplier

Switch statement

What if we have multiple powerups? Now I only have 3, Speed, Triple Shot & Shield. How do we know which one we pick? And use?

There’s gotta be a simple way to do so.

What about the If statement? That would work! Well… it would work yes, but if you have multiple powerups or anything else. It would get messy pretty easily. And it wouldn’t look good at all.

We use Switch statement! With this, we keep the code clean and easy to read and understand! :)

We have private int powerupID;
In our powerup script. With this, we know which powerup we have.

For example:
Triple Shot= 0
Speed = 1
Shield = 2

This is our code in the Powerup Script

So if the powerupID is 0, Speed. Case 0 will run, which uses the player.TripleShotActive();
And then it will break, which means that the code stops running.

And after switch statements, the game object will destroy itself.

Nice! The switch Statement is effective in these cases. Just remember to use break; them after assigning what they do! ;)

Thank you for reading this! And hope to see you at the next one! :)

Photo by Olga Subach on Unsplash

From the beautiful snowy country with a touch of "good" humor? Inspired Unity Developer to learn more.