In a previous article, you learned how to add a power up to your game. Most likely, if you’re adding one power up, you are going to add more (once you power-up, you just can’t stop). Let’s take a look at how to streamline your power ups by reusing a single Power Up script.
To set up the initial power up, you needed a script to manage the behavior of the power up — not the functionality it adds to the Player, but the way it moves down screen and how it collides with other objects. When creating additional scripts, much of that behavior will stay the same. So why not make use of the script you already have?
You can associate a power up ID to a type of power up, which allows you to track which power up is using the Power Up script at any particular time.
In the Unity Editor, select each power up prefab and assign an Power Up ID (ie. 0 to the Triple Shot power up and 1 to the Speed Boost power up).
Since the only thing that changes from power up to power up is what method it calls on the Player, we can specify which Power Up ID is associated to which method.
Within the collision method, check the Power Up ID and only call the method associated to that type of power up. With these changes, you can assign the same Power Up script to each Power Up you add — just assign a new Power Up ID and add a check for that ID in collision so it corresponds to the correct functionality.
Now, we have more lasers and more speed! What else can we do with power ups?