Switch statements — the cleaner if/else.

Neat, organized code is good code. Just because you can read it doesn’t mean the next programmer that comes along can. I really believe that if you can write nice clean code you are going to make your life a lot easier.

If/Else statements are awesome, powerful things. The problem I find with them is that they are ugly, messy lines that can be confusing. Anytime I have line after line of them I will move to a Switch statement. It just makes it so much neater and easy to read and it does the exact same job

Here, you find my messy If/Esle If code.

Here, is my nice, neat and tidy Switch statement.

See the difference? It just makes reading it so much easier.

So, how do we write it? What does the case or the break mean? I’m sure just by looking at it you can make sense of it, but for those in the back…

Note that this code is inside of an OnTriggerEnter2D and is checking if the other collider is the Player. So when the Player collides with one of those cases it will run the method inside.

So, the first case is 0 which is our TripleShot. If the player collides with out TripleShotPowerup, it is going to activate the TripleShot method, and then the next line is break. Break just means STOP! Stop right there. Leave the switch statement.

So if case 0 is not true (the Player did not collide with the Tripleshot powerup) then move to case 1. If it collides with the Speed power up, run that code and break (leave the switch statement).

That’s it, that’s all there is to the Switch statement. As I said, it’s no different that using an if/Else statement but cleaner.

Now on with the coding my game. I’m excited because I’m not beginning to work on the UI, or User Interface. Adding a Score, Menu, etc. Join me tomorrow and I’ll show you how to do a nice, easy UI!

Happy Clicking!