Chance to spawn an enemy with a shield

Adding an enemy shield that when enemy spawns, it randomly decides if that enemy has a shield or not.

In that, we can see clearly that some of the enemies spawn normally without a shield. And some spawn with a shield. How can we make this happen? Let’s start coding! :)

Enemy Script

This is how our Enemy Script looks like. We need these variables.

  • GameObject which is Enemy Shield,
  • Boolean which is Shield Active,
  • Float which is Chance To Spawn With Shield

In our GameObject, we choose the shield we want the enemy to have. And we set it false from the Hierarchy and set it true from our code.

Calculate Shield Chance

To make this happen, we need to calculate from the start when our enemy spawns to determine if that enemy has a shield or no. And this happens in Start Method.

In the start, I have an if statement to know if that enemy is _normalEnemy since I have this script attached to other enemies too. And with this, I can make sure that it doesn’t try to calculate this Shield Game Object to other enemies as well.

And the CalculateShieldChance looks like this, we only SetActive our GameObject and set the Boolean _shieldActive to true.

So what if our enemy takes damage? Does this shield take the hit and the enemy survives? Well… In our OnTriggerEnter2D where we damage our enemy, we check first if _shieldActive is true or not.

So when _shieldActive is true, we just disable our Shield and set _shieldActive to false and then we return. And if it’s not true, we destroy the enemy.

Awesome! Now our enemies have a chance too, maybe?
Thank you for reading and hope this was useful information. See you in the next one! :)

From the beautiful snowy country with a touch of "good" humor? Inspired Unity Developer to learn more.