Unity Development — AI Sight

You have some AI enemies that are moving to their waypoints and following a path properly. That is a great first step. If you want to reach the Metal Gear level or any other stealth game, you’ll have to make sure those enemies can see the player.

When we say we are going to give the enemy AI sight, we are really just going to use one of the basic Unity tools we have learned and manipulate it to seem like the seem that way. In actuality, we are going to use a trigger collider. On your enemy gameobject in the Hierarchy, add a child cube.

To help your organization, you can rename the cube to ‘Eyes’ or ‘Sight’ or anything else you’d like. Use the scale tool to stretch the cube out to the right size you feel is appropriate to represent the enemy’s line of sight and distance. You might even want to use a different mesh than a cube, it is completely up to you. You’re not actually going to want to see a shape on the enemy, so go to the Inspector and turn off the Mesh Renderer or simply remove. While you are there, make sure to change the Box Collider into a Trigger.

For the trigger to work, depending on whether or not your player gameobject has a Rigidbody, this shape is going to need a Rigidbody. Add one to be safe and be sure to zero out the mass, drag, and angular drag. Turn off gravity as well. Now you should have a proper trigger that is ready to function.

Make a new script to attached to your sight gameobject. Depending on your game, you can put whatever you want in the function after the trigger has been set off. For this example, I have a Game Over cutscene that is held on a gameobject with a Timeline Playable Direction. That object is activated once the player is caught. So that code looks like this.

As I said, you can place whatever you desire in there. Perhaps you want the player’s health to drop or for the enemy to then have an attack activated. The choice is yours.

--

--

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