Switch Statements To The Rescue!

Samantha Gittemeier
2 min readMay 24, 2023

--

In the last article we talked about Creating Modular Powerup Systems and we used if and else if statements to do it. Well, there is an easier way we can do this rather than using a bunch of those statements. Instead, we can use a Switch statement.

A Switch statement is a statement that switches using a variable, and calls for different cases. This again would start at 0 as all numbers do in Unity. It would look something like this.

Switch (variable)
{
case 0:
//call for logic here
case 1:
//call for logic here
case 2:
//call for logic here
}

So for me implementing it with the modular powerup system I have for my Triple Shot, Speed, and Shields, it would look like this.

Now you’re probably wondering why the cases are underlined in red, this is because they haven’t been told when to end. After the logic is called for a case we need a way to tell the case to end. The way we do this is by simply adding a break line after each case like this.

Now that you understand how we can use Switch statements you can find other scripts where you may have a build up of if and else if statements and instead use a switch statement where applicable.

--

--