Enemy Shields and Who Gets one!?

Objective: Create a shield for base enemy type and decided when they get one or not.

If creating different enemy types makes you base enemy types seem less powerful an easy way to strengthen that character type is to add a shield. It wouldn’t be fair to if we made every base enemy have a shield, so we are going to need to set a probability to who get a shield or not.

To begin we need a couple of variables for the enemy script. We need a bool variable for when the shield is active. We need a Game Object for the physical representation of the shield.

This is simple and vastly similar to the shield we added for the player. Bring the enemy prefab into the hierarchy and parent your sprite for your shield.

Set the shield to not active.

Open the enemy script. Inside I reworked my On Trigger Enter 2D method. This new set up made adding a shield simple. Every tag now calls on a method called damage. The damage method is where all the code for the score and the enemy destroyed happens.

Now we need to add an if statement for what we want to happen if the shield is active. At the top of the damage method, we add this statement, so we attack the shield first. If the shield isn’t active, then we attack the enemy itself.

Now we want to set up when the enemy has a shield or not. We begin my making a method. In this method we create a local variable and set it to random between 1–101. This will generate a number from 1 to 100 and we can use this to set a probability of if the shield is active or not. With the top amount being 100 we can set these values like percent.

We want to create an if statement for if the probability is 80 or higher than the shield is active and the visual is active. This creates a 20% chance that when a base type of enemy is instantiated it will have a shield.

Now we want to call this method from the spawn manager. In our coroutine that spawns the enemies. This will generate the random number every time we instantiate.

That’s all there is to it. Now we have a base type of enemy that sometimes has a shield making them harder to destroy. As always, don’t be afraid to experiment with your code, and I’ll see you in the next tutorial.

--

--

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