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)
Debug.Log("SPEED POWER UP");
Debug.Log("SHIELD POWER UP");
Debug.Log("Default value: powerupID")
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)
_isTripleLaserActive = true;
_isSpeedupActive = true;
_isShieldActive = true;
Debug.Log("Switch: default in Player.PowerUpType");
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:
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().