Too many ifs? Switch statements are to the rescue in Unity

Jaime
1 min readMay 1, 2021

--

Going back to my previous article Creating modular power up systems in Unity, if I had to make 40 power ups, then I would have to write as many if statements just to evaluate one variable, _powerupID. This would look redundant and messy.

private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.gameObject.GetComponent<Player>();
if (player != null)
{
if (_powerupID == 0)
{
player.TripleShotActive();
}
else if (_powerupID == 1)
{
player.SpeedActive();
}
else if (_powerupID == 2)
{
player.ShieldsActive();
}
/* and 37 more if statements */
}
Destroy(gameObject);
}
}

The cleaner and easy-to-read solution is to convert this into a switch statement which make the conditions clear and concise with less syntax:

private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.gameObject.GetComponent<Player>();
if (player != null)
{
switch (_powerupID)
{
case 0:
player.TripleShotActive();
break;
case 1:
player.SpeedActive();
break;
case 2:
player.ShieldsActive();
break;
default:
Debug.Log("Default");
break;
}
}
Destroy(gameObject);
}
}

Instead of if (_powerupID == 0) , it’s replaced with case 0: instead. If the case matches, the block of code within the case is performed. Also, the break keyword means that if this line is reached it will ignore the rest of the cases. On the other hand, the default case basically contains the block of code to be executed should there be no match at all.

--

--

Jaime
Jaime

No responses yet