Creating Modular Power up Systems
Today, let's create a power up modularity. Modularity allows us to use one script that will define different power up behavior and let us control the assignment of each power up a number. Without modularity, we would have long lists of scripts for power ups and have the screen all cluttered. “Yuck!” Let’s click on the sprites folder and bring up speed under power ups folder.
Click and drag the sprite to hierarchy and name it Speed Power up. Now add a box collider 2D and adjust the parameters and Is Trigger checked off. Also, add Rigid Body 2D and set gravity to zero and add power up script. Next go ahead and drag the speed power up down to the prefabs folder and delete the speed power up left in hierarchy.
Inside Power up script, create a [SerializedField} int private ID for power up. 0,1, and 2 will be the ID used to identify the different power ups. I could have used an if, else if statement for the different power ups as shown below. I commented out the scripts, so it won’t affect the logic.
I will be using a switch statement instead for a much organized and cleaner appearance. Here, numbers are assigned to the different power ups.
Next, go to spawn manager script and create a private game object: power up with [ ] array brackets to make a fixed list of power up items to be randomly spawned.
When done and saved, you should have power ups drop down menu in Inspector tab. The number inside the size box indicates how many items are going to be used for power ups.
Back inside the spawn manager script, scroll down to Power UP routine and script the following code to get the power ups to spawn randomly.
Let's also not forget to set up the co routine for the speed boost so that we will have a power down routine when speed power up is collected.
Now we have speed power up as well as triple shot power up spawned at random using the modular system instead of long else if statements.