I want power. Sure, who doesn’t? But power has its cost. It stands to reason that the more power I accumulate, the heavier the cost. It is worthwhile to streamline the power acquisition process, to spare me further cost than I can manage.
I have three powerups planned for the space shooter game. Does it make sense to create a C# script for each one? Seems like I’d be duplicating a lot of work. I need one powerup script that can account for all the powerup behavior in the game. Let’s take a look at how to do that.
I’ll create a new C# script and call it “Powerup.” I need movement (implemented in a similar way as the Player), and auto-destruct for missed opportunities:
In order to handle multiple powerups on this one script I need each powerup to have its own ID number.
Now I can go to each powerup prefab and assign it an ID in the Inspector. Next I will make a conditional statement for each ID to call out the proper powerup method in my Player script.
I’m using OnTriggerEnter2D to verify we’ve collided with a player. Then GetComponent to access the Player script. Finally, after informing the Player script what sort of power to trigger, I destroy the powerup.
This does the job, but there’s a lot of repeated text in this setup, what with all the “if, else if, else if” business. If I decide later that I want more than these three powerups (spoiler: I will), it could get cumbersome. I’ll need help to keep things as streamlined as possible, or the cost of more power will be too steep.
Next article, switch statements will come to our rescue.