A Modular Power Up System

The ability to switch random power ups

Now that we have more than one type of power ups, its time to create a system which can house all of the game objects and freely spit them out into the game field at randomly. There are many methods in completed this, we can use an infinite “if and else if” statements, but that is very inefficient especially when you have multiple of power ups in the future, not to mention not very optimized on both hardware and software side.

In Unity, instead of having an immense line of “if and else if statements” we have something called “switch”. The switch statement is very easy to understand and implement as well.

The switch statement in Action with 3 different case logic

Like any other codes, the switch statement is the same, it works by typing “switch” and initializing it with brackets. In this example, we are initializing a private integer power up ID. Below we have something called cases, and all cases start with zero. Each case can contain a different type of game object. In the example above, case zero is containing the triple shot power up. We also write the logic within the cases within, so for example the case zero is where we call the triple shot power up.

Assigning the Unique game object ID which can be identified by the switch command.

Once we have our desired amount of cases, we end the list with “default” to prevent any errors or undesired case logic from happening. We also end each case with “break”. Back on the inspector, we now have to manually assign each power up game object their unique ID.

The modular system should be working once you have assigned the proper IDs to the game object. With the switch statement, it is a lot easier to control and execute a list of different game objects.