Objective: Randomly Spawn enemy with shields!
To start his part of the journey off, we’ll need to apply the shield in the same manner as the player. First thing will be to add a shield object as a child to each enemy prefab.
Next, let’s change the color a little so it’s not the same as the player. To do this, on the shield we’ll just change the color. This will add the color to the current color of the shield, so we need a red tint to the blue.
To follow this up, we’ll need to get a reference to the shield. Let’s move to the Enemy base class and add it in. We will also add in a bool to check to see if the shield is active or not.
After creating the reference, don’t forget to assign it in the inspector.
Back in the enemy script, in the start function, let’s call the function to see if we will have a shield or not on spawn. I named it EnableShield.
Now let’s create the function. Inside we will pick a number between 0–5, but using Random.Range() with int’s, the max number we input will not be used but the number before it. So if we put 5 the range will be 0–4, therefore we’ll put 0–6.
We’ll than use an if statement to check to see if the random number is equal to or less than 1. If so enable the shields and set the bool to true.
Now to allow the enemy to get a hit and not take damage while the shields are active. In our OnTriggerEnter2D, when the trigger is activated and checks to see what hits, we call our OnHit function. Inside this function we check to see if the shields are active, if they are deactive the shield and turn the bool to false. If the shields are not active damage the enemy like normal.
Since we do have another enemy that does override this OnHit function just a little let’s look at what we need to do with it.
In our ZigZagType script, use override our OnHit to delete the waypoints parent object after the enemy has died. Therefore we don’t want to delete them when the shields are destroyed. We’ll check to see if the shields are not active, if so destroy waypoints. After that call the Base class OnHit like normal.
And there you have it! We now have enemies that will spawn in randomly with a active shield! Thank you for reading!