Enemy firing when detecting player

Let’s go over the implementation of an enemy that fires when it detects a player.

The basic enemy was added in this article, and the look of the enemy was changed in this article.

Open up the Enemy script and add another value to the PlayerType enum for the new enemy:

In Start function set this enemy to be able to fire as soon as the player has been detected:

In the Update add a Raycast that start just above the enemy to ensure it does not detect itself. Set the direction of the ray to upwards. If the Player is detected, then shoot:

Update the Shoot function to allow the new enemy type to shoot again after 1 second:

Add a case to the switch statement inside the EnemyMovement function for the new enemy. This enemy will come in from the side and then move back and forth below the player until it has been destroyed:

Open up the enemy script and update the spawn routine to spawn this enemy outside the left side of the screen:

Duplicate the standard enemy projectile object and rename it. Open up the prefab and reverse the direction of each projectile:

Add the new projectile object to the new enemy:

Lastly, add the enemy to the SpawnManager on the Inspector:

Good luck!



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