As of now, the Space Shooter game allows the player to receive 3 types of power up to improve the ship: Triple Shot, Speed and Shields
Each of these power ups should have a script to tell the Player what kind of effect will be activated when the Player triggers it by colliding with it. Now, this would be hard to maintain if you have 20–50 power ups since you will need to create that many scripts as well.
Fortunately, you can make it modular by using the same script on all power ups, and simply use a unique identifier for each power up. In the game, I used a unique integer variable to differentiate each power up:
0 => Triple Shot
1 => Speed
2 => Shield
As you can see from the Speed_Powerup prefab, Powerup ID is set to 1:
From the source code, Powerup.cs, you can see that the message sent to the Player is different based on its current _powerupID when it is triggered:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Powerup : MonoBehaviour
{
[SerializeField]
private float _speed = 3.0f; [SerializeField] //0 = Triple Shot 1, 1 = Speed, 2 = Shield
private int _powerupID; void Update()
{
transform.Translate(Vector3.down * _speed * Time.deltaTime);
if (transform.position.y <= -6)
{
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.gameObject.GetComponent<Player>();
if (player != null)
{
if (_powerupID == 0)
{
player.TripleShotActive();
}
else if (_powerupID == 1)
{
player.SpeedActive();
}
else if (_powerupID == 2)
{
player.ShieldsActive();
}
}
Destroy(gameObject);
}
}
}
If you were to add another power up, you simply need to add this C# script to the new Powerup prefab, assign it a Power ID and add another else-if condition in the code to specify its message to the Player.