Modular Power-Up System
Object Oriented Programming is all about modularity. Modularity is a system property which measures the degree to which densely connected compartments within a system can be decoupled into separate communities or clusters which interact more among themselves rather than other communities. For the 2D Space Shooter, three different power-ups are spawned all using the same script. Within the same C# script, a private integer defines which power up is carrying the script, therefore identifying which action to trigger upon collision with the player.
[SerializeField]
private int powerUpID;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Player player = other.transform.GetComponent<Player>();
if (player != null)
{
if(powerUpID == 0)
{
player.ActivateTripleShot();
}
else if (powerUpID == 1)
{
player.ActivateBoost();
}
else
{
player.ActivateShield();
}
}
Destroy(this.gameObject);
}
}
Listing the prefabs of power-up collectibles through an int variable creates the modular switch that channels a specific method. To optimize the collision trigger of each power-up method, the switch method lists the prefab through much shorter cases:
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Player player = other.transform.GetComponent<Player>();
if (player != null)
{
switch(powerUpID)
{
case 0:
player.ActivateTripleShot();
break;
case 1:
player.ActivateBoost();
break;
case 2:
player.ActivateShield();
break;
}
}
Destroy(this.gameObject);
}
}
Modularity is a pretty wild concept on a simple and eloquent method.