Adventures in GameDev with GameDevHQ! Day 24: switch statements to the rescue!
So we’ve built our modularized powerup system, and we wrote a system that checks for 3 powerups with a series of if/then statements. But what if we have 5 powerups? 10? what if we build a skill tree of potentially 30 or more different style powerups? That’s a whole lotta typing!
Fortunately, there’s a more streamlined way we can check a single variable to see if they’re equal to a series of values, that is in our case, we can check our _powerUpID against the values of 0 through 2.
Ah! Much more streamlined! Of course you won’t want to use switch statements for everything, but if you have a lot of conditions that are checked against a single variable, this may be the method for you.
Let’s go to our PowerUp and see it in action!
Looks a lot cleaner, doesn’t it?
So after getting a reference to the player and checking to see it exists, we then check the _powerUpID, (0 = Tripleshot, 1 = speed, 2 = Shields). If it hits case 0 and its true, the we Activate the TripleShot function. Then it breaks which basically says “Stop right there! Don’t do anything else! Go home now!” and it breaks out of the function.
Let’s say it was 2 that was the _powerUpID. Case 0 wasn’t 2 so it gets ignored. Same with Case 1. But then we reach Case 2 and we get a match; Activate shields in the player script gets activated and then break stops everything and returns us to our normal programming. Easy enough!
As another example, since I was writing 3 different FinishPowerUp functions for each individual powerup. This is slightly messy, could I just write one FinishPowerup routine and use the switch case statement? Turns out I was able to with a bit of GetComponent magic! Since the powerUpID was in the powerup itself, and the FinishPowerup was in the player, I used GetComponent to have the PowerUp send the PowerUpID information to the player! First I set up a variable in Player:
Notice that the variable is public, this is important because other scripts will now be able to access it.
Next in the powerups OnTriggerEnter, I accessed the player through GetComponent and assigned its powerUpID with the Powerups variable, _powerUpID. Notice the underscore, the powerups own powerUp variable is a private one that can’t be accessed from the outside but we were able to funnel a copy of it into the player!
Next, we create one FinishPowerUp function that uses a switch case using the copy of the powerUpID so it will know what to do depending on what number it gets back:
Since we know what powerUpID is because the power up itself sent us the information through GetComponent, we’ll be able to switch through the different cases appropriately and we’ve cleaned up our code rather significantly by combining 3 different function calls into one!
Next we’ll be getting into User Interfaces in Unity. Stay tuned!