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
_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;
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;
Most of the logic for when the enemy and the player collide is in the
Here’s a collision check for projectiles:
Destroy(other.gameObject); if (_isShieldActive)
_isShieldActive = false;
} _isDead = true; if (_player != null)
_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!