Simplify Your Code With a Switch Statement
This has been a heavy week working on some really exiting projects. :D
So it’s just a short one today…
In games we often need to check for a number of values. The code can quickly become hard to read if we don’t optimize it.
An example from the Space Shooter game we looked at before. Let’s say we give our player different enhanced abilities, which we call power up. One is a triple shot, one a speed boost and the third one a shield. The player can collect them while playing. To test which power up the player collected and thereby needs to be executed, the obvious way is to add a series of if and if else statements.

While this works, it becomes cumbersome when we have a large number of options. Imagine having 50 if and if else statements in your script!
An easier way to do this, is to use a switch statement. We simply define the variable we want the switch to check for and then define the different cases with instructions for each case.

It does look neat, doesn’t it?
What if we get a value that has not been defined? We can add a default case which is automatically applied if the value is not defined.

Give it a try!