Creating A Modular Powerup System
In the blog post from day 14, we successfully implemented the triple-shot power-up, granting the player a formidable ability to vanquish enemies. But what if we have multiple types of power-ups? Would we need to create a separate script for each one? The answer is a resounding no! Since our power-ups exhibit similar behavior, we can employ a single script to “rule them all!”
This brings us to a crucial programming concept known as modularity, which involves combining various components to create a cohesive and functioning entity. In our case, we can utilize one script to control all our power-ups, regardless of whether there are 3, 10, 50, or more.
Next, we’ll assign a unique ID to each power-up for identification purposes. To achieve this, within the PowerUps script, I’ll create a private integer variable called _poweruUpId and assign a specific value to each power-up through the inspector. For instance, the triple-shot will have an ID of 0, the speed boost will have an ID of 1, and the shield will have an ID of 2.
[SerializeField] private int _powerUpId;
Afterward, we can add the necessary logic to our OnTriggerEnter2D function to handle power-up collection:
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Player player = other.GetComponent<Player>();
if (player != null)
{
if (_powerUpId == 0)
{
Debug.Log("Triple Shot Collected");
} else if (_powerUpId == 1)
{
Debug.Log("SpeedBost Collected");
}
else
{
Debug.Log("Shield Collected");
}
}
Destroy(this.gameObject);
}
}
And voila! Our code functions exactly as intended!
However, imagine the chaos if we had to write 50 if statements for 50 power-ups! It would be an absolute nightmare. Therefore, we need a more efficient way to optimize our code. In the next article, we’ll delve into how to achieve just that.