Switch Statements to the Rescue

Renato Figueiredo
2 min readDec 5, 2023

Objective: Learn how to use switch statements to prevent overuse of else if statements.

When we created our modular system for powerups, we ended up using if statements to check for our PowerupID. The problem is, when the game gets more powerups, we need to add a bunch of else if statements, which is something that all developers must avoid.

private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.GetComponent<Player>();
if (player != null)
{
if(_powerUpID == 0)
{
Debug.Log("TripleShot Collected.");
}
else if(_powerUpID == 1)
{
Debug.Log("Speed Collected.");
}
else if (_powerUpID == 2)
{
Debug.Log("Shield Collected.");
}
}
Destroy(gameObject);
}
}

Now we are going to simplify the code above, using a Switch Statement. Switches allows us to filter through a variable, and check if its value is a specific one, and in case it is, we can just execute that specific case.

 private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.GetComponent<Player>();
if (player != null)
{
switch (_powerUpID)
{
case 0:
Debug.Log("TripleShot Collected.");
break;
case 1:
Debug.Log("TripleShot Collected.");
break;
case 2:
Debug.Log("Shield Collected.");
break;
default:
Debug.Log("Default value.");
break;
}
}
Destroy(gameObject);
}
}

Using the same logic as before, we have a message for each powerup collected, but instead of having multiple else if statements, one for each scenario, we now have one Switch Statement, that contains the specific for each scenario.
We can also add a default scenario to our switch, meaning that if the value is different than all cases stated on the switch, it will always run its default.

Now with these changes, we have a much cleaner and easier way to check which powerup is being collected by our player.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response