Enemies with Shields

Christian Carter
2 min readAug 23, 2021

This tutorial will go over how to give some enemies shields. This will reuse the shields from the player and implement them in a similar way. Though the enemy shields will only take one hit. To start go to the Enemy script. Add two variables at the top. One for if the shield is active and another to control the shield visualizer.

[SerializeField] private GameObject _shieldVisualizer;
private bool _isShieldActive = false;

Next, you will need to go to the Unity editor. Click the dropdown for the player in the Hierarchy. Select the shield and copy it. Open up the Enemy prefab and paste the the shield into it. Now open up the Enemy in the inspector. Drag and drop the shield into the Shield Visualizer space. Then save and close the Enemy prefab.

Next, go back to the Enemy script. Create a function called ActivateShield. This may be used by the SpawnManager script in the future so set it as a public function. In the function set the shield is active bool to true and set the visualizer to active.

public void ActivateShield()
{
_isShieldActive = true;
_shieldVisualizer.SetActive(true);
}

Next go to the Start function of the Enemy script. Add and if statement with that generates a random range from 0 to 1. When it returns 1 activate the shield. This will give enemies shields half of the time. Later you can remove this portion if you ever add it to the SpawnManager.

if (Random.Range(0, 2) == 1)
{
ActivateShield();
}

The last step is to update the OnTriggerEnter2D function. In this function you need to add two checks for if the shield is active before the enemy is destroyed so that if it has a shield that is removed instead. One when the other collider is the Player and another for when it is a Laser. When the enemy has a shield and hits the player it will damage the player twice. See the code below for specifics.

private void OnTriggerEnter2D(Collider2D other
{
if (other.transform.tag == "Player")
{
Player player = other.transform.GetComponent<Player>();
if (player != null)
{
if (_isShieldActive == true)
{
_isShieldActive = false;
_shieldVisualizer.SetActive(false);
player.Damage();
}
player.Damage();
}
EnemyDeath();
}
else if (other.transform.tag == "Laser")
{
Laser laser = other.transform.GetComponent<Laser>();
if (laser.GetIsEnemyLaser() == false)
{
if (_isShieldActive == true)
{
_isShieldActive = false;
_shieldVisualizer.SetActive(false);
Destroy(other.gameObject);
}
else
{
if (_player != null)
{
_player.AddScore(10);
}
Destroy(other.gameObject);
EnemyDeath();
}
}
}
}

Now some of the enemies will have shields.

-Chris

--

--