My journey becoming a Unity game developer: Switch Statements to the Rescue.

Objective: Replacing IF/ELSE statements with SWITCH statements to activate each powerup. Also, setting up the Speed Boost and Shield behaviors through code and animations.

Player collecting powerups using the SWITCH statement.

Let’s start by setting up the Speed Boost and Shield activation inside the PlayerBehavior script. Create 2 new variables Type Bool name _isShieldActive and _isSpeedBoostActive which will be set to False as their defaults.

Next, create 2 IEnumerators name SpeedBoostPowerDownRoutine() and ShieldPowerDownRoutine(). Yield return new WaitForSeconds of 5 seconds to allow the powerups to stay active. Then use the 2 variables for their respective coroutines and set them to False to turn off the powerups.

Now, create 2 new methods name SpeedBoostActive() and ShieldActive(). Use their respective variables, and set them to True to active their powerups. Then, use the StartCoroutine() function and pass in their respective coroutines to set the powerups to stay active for 5 seconds, then turn off.

Speed Boost and Shield methods, plus coroutines are created to check if they’re active.

We’re now able to collect all 3 powerups in the game.

Player able to collect all 3 powerups.

To set the Speed Boost to move the player at a faster speed, let’s create a new SerializeField Private Type Bool variable name _speedMultiplier. Set its value to 2f, as we will multiply this value with the Player’s speed to double its speed amount.

Speed multiplier created to double the speed of the player’s movement.

Now our instinct will be to use the _speedMultiplier inside the PlayerMovement() method. However, this will be a bad spot to use this variable as we will be changing the _speed variable’s value and not being able to set it back to its original value that easy.

The player moving at normal speed through Translate.

A better way of increasing the Player’s speed after collecting the Speed Boost powerup will be to go inside the SpeedBoostActive() method. Inside there we will increase the Player’s speed by taking the _speed variable and multiplying it by the _speedMultiplier variable to create a new _speed value.

Using the speedMultiplier to increase the speed when Speed Boost is active.

Now that the Player’s speed is double the amount, we need to set it back to normal when the Speed Boost is deactivated. Inside the SpeedBoostPowerDownRoutine() coroutine, take the _speed variable and divide it by the _speedMultiplier to set the _speed variable back to its original value.

Used the Speed Boost PowerDown Routine to return the player’s speed back to normal.

Go to the SpawnManager’s script as we’re going to spawn the powerups randomly. With the _powerupPrefabs variable, add the array brackets ‘[]’ behind Type GameObject to turn this variable into an array of powerups.

Go to the SpawnPowerUpRoutine() coroutine, and add the array ‘[]’ brackets behind the _powerupPrefabs variable inside the Instantiate() method. Then, create a new variable Type Int name randomPowerup with a Random Range from 0 to 3. This will represent the 3 powerups we have in the game so far. Back inside the Instantiate() method, add the randomPowerup variable inside the _powerupPrefabs[] array bracket. We will now see different powerups appearing randomly onscreen at random positions and at random times.

Powerups will be instantiated randomly through an array.

Over in the PowerUps script under the IF _powerupID==1 condition, add player.SpeedBoostActive() to activate the Speed Boost when condition is met.

Speed Boost Active() assigned to powerupID #1 when collected.

On the Spawn Manager object under the Spawn Manager script component, change the Powerup Prefabs variable value to 3 for the amount of powerups we have. Drag each powerup prefab into their respective element slots with Triple Shot 1st, Speed Boost 2nd, and Shield 3rd.

Powerups assigned in the Powerup prefabs array variable inside the Spawn Manager object.

When we play the game, we can now use the Speed Boost for 5 seconds before they’re deactivated.

Speed Boost activate when its powerup is collected.

Back in the PowerUps script, under the IF _powerupID==2 condition, add player.ShieldActive() to activate the Shield when this condition is met.

Player made indestructible for 5 seconds when shield is active.

We’re now indestructible for 5 seconds after collecting the Shield powerup before deactivation.

Player protected for 5 seconds after collecting a Shield powerup.

To visually see the force field around the ship, drag one of the Shields sprites onto the Player game object. Rename the sprite to Shield, open Animation tab, select Create button, and name new shield animation. Select all of the Shields sprites and drag them into the Animation dopesheet’s timeline.

Shield game object created to show force field around the player.

If you want to animate the force field further, click on Add Property and select Transform->Scale. Click the REC button and using the 0, 8, 16 keyframe, adjust the scale along the X or Y axes to make the shield animate to your liking. Turn off the Shield game object as the shield will be turned on through code.

Shield animations updated inside the Animation’s dopesheet.

In the PlayerBehavior script, create a new variable with a SerializeField Private Type GameObject name _shield to hold the Shield game object. In the ShieldActive() method, turn on the shield by using _shield.SetActive(true). In the ShieldPowerDownRoutine() method, turn off the shield using _shield.SetActive(false).

Shield turned on when active, and turned off when inactive.

When the player collects the Shield powerup, we will see the shield around the player for 5 seconds before disappearing.

Shield activated for 5 seconds, then turns off.

Now we have been activating the powerups using IF/ELSE/IF statements, but as we add more powerups to the game we will run into very messy looking code that will be hard to read. That’s were the SWITCH statement comes into play. The IF statement executes based on the value of a Boolean expression using a single-selection structure, and IF/ELSE using a double-selection structure. While, SWITCH statement selects a statement list to execute based on a pattern matching an expression value.

The SWITCH statement is setup basically in the following format:

The SWITCH statement works in the following way:

  • The SWITCH expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • When there is a match, the associated block of code is executed.
  • The break keyword breaks out of the SWITCH block ignoring the execution of all the rest of the code in the SWITCH block.
  • The default keyword is optional and runs specific code if there’s no case match. Default can be used anywhere inside the SWITCH block, but it’s considered best practice to use it at the end of the block.

This is how our code is setup through the IF/ELSE/IF statements with 3 conditions to check through so far.

If/Else used for activating powerups.

Now using the SWITCH statements, we will evaluate our expression which will be the _powerupID list. When a powerup is collected by the player, that _powerupID value will be compared with each CASE value until there’s a match. If a match occurs, the code block will be executed which in this case will be that player’s method to activate that particular powerup. Then the BREAK will stop executing the rest of the code in the SWITCH block.

The pattern we’re using to activate the powerups will be the constant pattern. This pattern will test if an expression result equals a specified constant.

Using a SWITCH statement to activate powerups.

Player is now activating the powerups when collecting each one through the SWITCH statements.

Player collecting powerups using the SWITCH statement.

There is another pattern called a Relational pattern that is popular to use with a SWITCH statement. With the Relational pattern you compare an expression result with a constant. You can use any of the relational operators like (<, >, < =, or > =). In this example, we switched out the constant numbers to match and replaced them with relational operators to compare for a match with.

SWITCH statement using Relational patterns to activate powerups.

Player still able to activate powerups collected using the Relational pattern.

Player using powerups through Relational pattern in SWITCH statement.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store