2D Galaxy Shooter P2: Enemies can now have Shields!?

The challenge to adding enemy shields is complete!

The objective was to have some enemies spawn with shields. So the first thing I did was add a lives and a max lives variable of type int to the enemy script. I also added a GameObject variable that will hold the shield game object. One last variable to add is a bool to check if the shield is activated.

[serializeField] private GameObject = _shieldPrefab   = null;[SerializeField] private int          _lives          = 1;
[SerializeField] private int _maxLives = 1;
[SerializeField] private bool _isShieldActive = false;

I make sure that lives are always set to the max lives in the Start() function.

_lives = _maxLives;

I also want to make sure that only some enemies can spawn with the shields activated. So I created a local variable in the start function that will hold the percentage of enemies with shields.

float shieldProbability = 0.2f;

We need to check if Random.value is less than the shieldProbability variable. If it is, then to make sure this instance of the enemy has its shield activated.

if (Random.value < shieldProbability)
{
_isShieldActive = true;
_shieldPrefab.SetActive(true);
}

Random.value will generate a random value between 0 and 1.

Since enemies now have lives, we need to make sure when they collide with a projectile or the player, we take away a life or destroy the game object if there are no lives left.

private void TakeDamage(int amount)
{
_lives -= amount;
if (_lives <= 0)
{
_isDead = true;
Destroy(gameObject, 2f);
}
}

Most of the logic for when the enemy and the player collide is in the OnTriggerEnter2D() function.

Here’s a collision check for projectiles:

if (other.gameObject.CompareTag(“Projectile”))
{
Destroy(other.gameObject);
if (_isShieldActive)
{
_isShieldActive = false;
_shieldPrefab.SetActive(false);
return;
}
_isDead = true; if (_player != null)
{
_player.AddScore(_givePoints);
_player.AddAmmo(_giveAmmo);
}
_animator.SetTrigger(“isDestroyed”);
_movement.Speed = 1f;
_audioManager.PlayExplosionSound();
_collider.enabled = false; TakeDamage(1);
}

In bold, we check to see if the shield is active. If it is, then we set it to false, deactivate the shield game object, and return. We return because we don’t want to execute the rest of the code in the block.

Here’s the result:

The first shot took out the enemy shields, and the second destroyed the game object.

That is all for today! For tomorrow’s challenge, I will implement a balanced spawning system!

Thank you for your time!

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store