Objective: Use switch statement to implement a shield powerup for the player.

Switch statements are used when a single variable has multiple cases such as powerups or inventory. As shown below the Shield_Powerup is a prefab game object with an Is Trigger Circle Collider 2D, Rigidbody 2D with 0 gravity and Powerup script with _powerupID set to 2. The _powerupID integer variable is used by switch to select different cases in the Powerup script.

The switch statement is modular so that it is easy to add new cases. For example, the shield powerup is added to the Powerup script, as shown below, by adding a new case, case 2, which is called based upon the _powerID variable set in the prefab. On collision the function ActivateShields() on the Player script is triggered.

The shield itself is a Boolean variable, _isShieldActive within the Player script. The _playerShield game object is assigned using a [SerializeField] and is a child of the Player, providing the visualization for the shield. The ActivateShield() function called by switch case 2 toggles _isShieldActive to true and uses _playerShield.SetActive(true) to turn on the shield visualization. On acquiring the powerup, the player is immune to damage from enemies. The DamagePlayer() function checks _isShieldActive, and if true sets the _playerShield.SetActive(false), avoiding damage with the return statement, as shown below.

Calling the different powerups using the switch statement is efficient, allowing the developer to focus on providing unique content for each powerup.

Software engineer