Shields for enemies

Objective: Give some enemies a shield which blocks one hit.

Some enemies now have shields.

Take the Enemy prefab and drag it into the scene, and set position to (X 0, Y 0, Z 0). Copy the Player’s Shield and paste as child of the Enemy. Change shield position to (X 0, Y 0, Z 0) and set the shield’s scale to 1.0 for X, Y, Z. Make sure the shield is inactive. Apply overrides to the Enemy prefab.

Enemy with inactive shield.

Add private Transform _enemyShield = false to the Enemy script. Assign the Shield that is a child of the enemy using the C# code below, gameObject.transform.Find(“Shield”). The gameObject.transform.Find searches children of the transform. Do not use GameObject.Find, which searches all game objects.

When an enemy spawns it runs the Enemy script and assigns the _enemyID, which defines its behavior. In the script below, a random integer is generated from 0 to 3, thus 25% of enemies will have shields active and an _enemyID of 2.

On colliding with either the Player or a Laser, if the _enemyShieldOn is true the enemy avoids damage using the return command. Before executing the return command _enemyShieldOn is set to false and the animation for the shield is inactivated.

Damage nullified by shield in Enemy script

The enemies are now shielded and more dangerous.

--

--

Unity Developer

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