Switch Statements To The Rescue

Austin Hall
3 min readOct 6, 2022

--

As we add features and functions to our game, the code becomes more complex. In the case of our powerups, the if statements can get very messy as we continue do add more.

Shield Powerup

One the ways we can clean up our code and reduce the number of lines we are typing, is using switch statements.

A single switch statement can take the place of multiple if statements. This means less code written and something that is more easily read and understood.

The switch statement will go in our Powerup script. We will create a private variable for the powerup ID and use it to check for player collisions with the various powerups.

Not only is this a much cleaner look but it also runs faster, so our program wont be bogged down by the if statements.

Now that we have our shield powerup spawning with the others, we need to take care of the other portion of the shield powerup… The actual shield! We can create a game object for the Visual representation of the shield using the Player_Shield sprite. To make it follow the player when active, we set is as a child object of the player. Using the check box in the inspector, we can set its default state to inactive.

We need to create a game object variable for the player shield.

We’ll use the inspector to add the reference for the shield object. With the player object selected, click and drag the shield object into the reference box.

In Unity, there is a method called SetActive(). This method uses true and false to enable and disable an object. Now we can go to our player script and update it to turn our shield on and off, using the SetActive() method.

Damage and Shield Methods In Player Script

--

--

No responses yet