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
- 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.
2. Add behavior script to enemy shield
The enemy shield needs a script to control two aspects: the shield visuals, and the 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.
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.
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.
And finally, we can see this in action.
Thank you for your interest!