Advanced Power Up System
Triple Laser, Speed Up and Shields
--
In this article we cover how to create a advanced system for power ups. This makes it easier to create more power ups and manage them. Instead of creating a script for each power up we reuse parts that do the same things for efficiency.
Powerup Script — PowerupIDs
1. Add [SerializeField] private int powerupID; to the Powerup script
2. In the Inspector set ID for each of the powerup prefabs
3. Add switch statement to include the ID to call the right powerup function
private void OnTriggerEnter2D(Collider2D other)
{
//if collision tag is Player
if (other.tag == "Player")
{
//get player script //activate power up triple shot
Player player = other.transform.GetComponent<Player>();
if (player != null)
{
switch (powerupID)
{
case 0:
player.PowerUpPickUp("TripleShot");
break;
case 1:
Debug.Log("SPEED POWER UP");
break;
case 2:
Debug.Log("SHIELD POWER UP");
break;
default:
Debug.Log("Default value: powerupID")
break;
}
}
Destroy(this.gameObject);
}
}
SpawnManager Script — Prefabs and PowerupIDs
1. Add [SerializeField] private GameObject[] PowerUpPrefabs;
This allows us to add multiple prefabs through the inspector. Keep the corresponding PowerupIDs in mind. If necessary comment out parts of the code tat still refer to the old prefab.
2. Add the following code to spawn random power up. Random.Range the 2nd value is exclusive, so make sure that number is 1 higher then the higher number PowerupID you’ve got.
Instantiate(PowerUpPrefabs[Random.Range(_minPowerupID, _maxPowerupIDplusOne)], spawnPos, Quaternion.identity);
Player Script — Switch Statement
In our case we add our code effects of the power ups here. Using a switch statement for each power up type. With one public function only we can get the type of the power up and go into the switch.
public void PowerUpPickUp(string PowerUpType)
{
switch (PowerUpType)
{
case "TripleShot":
_isTripleLaserActive = true;
StartCoroutine(TripleShotCooldown());
break;
case "SpeedUp":
_isSpeedupActive = true;
StartCoroutine(SpeedUpCooldown());
break;
case "Shield":
_isShieldActive = true;
break;
default:
Debug.Log("Switch: default in Player.PowerUpType");
break;
}
Powerup — Speed Up
Multiplies the Player speed for a fixed duration.
Powerup — Shield
With the shield power up the player can take 1 hit without health decreasing.
The visual part is a animated game object shield that is a child of the Player game object. Which is activated and deactivated with:
_shield.SetActive(true);
Note: If gameobject is disabled when play button is pressed it can’t be found with GameObject.Find
When needed disable the game object in Start().