Giving your AI sight in Unity

There are a few ways of allowing AI to “see” in Unity. We’ll go over using Raycasts and simple box colliders here.

The easiest is to simply attach a game object (with a collider) to your AI and check if there is a collision between the game object and the player. We can use a custom shape like a cone or just simply add a cube, remove the Mesh Renderer and scale the collider:

With the collider selected, enable the “Is Trigger” option and make sure either the player or this collider also have a Rigidbody component attached:

Don’t forget to disable “Use Gravity” if the object doesn’t require it

At this point we just need a simple script that checks for the OnTriggerEnter event that looks for interaction with the player:

Make sure you have tagged the player as “Player”

Another other option is with a Raycast. Here we can better visualize ‘line of sight’ from the perspective of the AI.

In order to first get a feel for the position and length of the ray, we will create an empty game object and use a Debug.DrawRay() statement:

The result in the Scene view will look something like this:

Now that we are happy with the length and rotation of the ray, we need to implement the code that will detect the player:

Note: use transform.forward for local space. If you use Vector3.forward, the ray will ignore any local rotations



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