Journal 40 — Random Enemies Now May Have Shields in Unity

In this article, I will go over how I added in a way for random enemies to have shields.

The basic approach is as follows:

Random generation of shield when enemy is instantiated → Enemy shield checks for a collision → Enemy shield allows for a free hit on enemy without destroying the enemy

  1. Create shield style for enemy.

To start, we already had generated a shield for the player, so I copied this version, modified the color and size, and turned it into a prefab. Make sure the shield’s collider size is larger than the enemy, so the shield takes the collision.

Unity Editor, player shield and enemy shield

2. Add behavior script to enemy shield

The enemy shield needs a script to control two aspects: the shield visuals, and the collision.

Unity C# script for Shield, control visuals and collision

3. Add as a Game Object to the enemy prefabs

Now that the enemy shield prefab is created with script, we can update the base Enemy class to add the shield prefab. This way if the enemy shield is selected when instantiated, we can set the visuals on and check for collisions.

4. Update Base Enemy Class Script

In the base enemy script, we need to update two aspects: the shield is instantiated and made a child of the enemy prefab only after a random number selection is successful, and the enemy collisions need to be updated to allow for a free hit to the enemy if they have shields.

Unity C# script for base enemy, random generation of shield on an enemy

As you see in the above script, we instantiate the shield and make it a child of the enemy, we set the shield active, and we set a bool variable true that the enemy has a shield.

Unity C# script for base enemy, switch statement for collider

In the collider, I changed the script to a switch statement, where if the enemy collides with the player, laser, or shield while having their own shield active, it doesn’t damage and destroy the enemy.

Unity C# script for base enemy, switch statement (cont’d)

And finally, we can see this in action.

Unity Playmode with enemy shields active

Thank you for your interest!

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.