Feature: Enemy Shields

This article will show how to give the Enemy a random chance for an active Shield. Implementing this is similar to the Player Shield, covered in two previous articles, one with the base Shield and the other allowing the Shield to take multiple hits.

Add the Shield Visual from the Player to the Enemy Prefab.

In the Enemy script, we will need all of the Shield variables from the Player script. Which are int for the maximum Shield strength, an int for the current Shield strength, a GameObject for the Shield Visual, a bool to know if the Shield is active, a SpriteRenderer for the Shield’s renderer, and the three Colors the Shield will change to depending on the current strength. The only variable that needs to be added is a float for the chance of having a Shield.

We will also copy the ChangeShield method from the Player script for the Enemy script, which will change the Color of the Shield depending on the current Shield strength.

Create a new method that will determine whether the Enemy gets a Shield. Have it take in a float argument for the percentage. In the method, add a local float that will be the random chance that the Shield will be active and that will be a random float between 0 and 1. Next is an if statement to check if the percentage is greater than randomChance; if so, set _isShieldActive to true, enable the _shieldVisual, set _currentShieldStrength to _shieldStrengh, and call ChangeShield passing in _currentShieldStrength. For everything else, disable the _shieldVisual.

In Start, set the _shieldRenderer to the SpriteRenderer component of the _shieldVisual, and the _fullShieldColor to the _shieldRenderer’s Color. Then call the ShieldChance method passing in _chanceOfShield, to see if the Enemy gets an active Shield.

In OnTriggerEnter2D, inside the if checking for the “Omni Shot” Tag, create an if statement checking if the Shield is active. Then subtract one from the _currentShieldStrength, check if it is still greater than zero. If so, call ChangeShield passing in the _currentShieldStrength, and then end the method with a return. For everything else, set the _isShieldActive to false, disable the _shieldVisual and end the method with a return.

Copy the if and add it to the “Laser” Tag check, but after the Laser is destroyed.

Also, add it to the “Player” Tag check after the Player has been null checked, and ChangeLives has been called. That will make sure the Player still takes damage.

The Enemy now has roughly a 50% chance of having an active Shield when they spawn, and it acts just like the Player Shield.

Unity Developer, Software Engineer, Game Designer

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