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




Unity Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A Quick Introduction to the Programming Terms: Python Complete Course

Expanding disk size in CentOS8

Codica Named Top Web Development Company in Ukraine by Clutch

Politics live updates: Pennsylvania AG rebukes Trump for falsely claiming he won the state

Troubleshooting Azure CLI issues on Debian

How To Create A GitHub Profile README 📝

Data visualization as easy as <HTML>

Hire a Dedicated Software Development Team

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
Mike Brisson

Mike Brisson

Unity Developer

More from Medium

Unity Counterparts in Unreal Engine

Adding a burst laser powerup

Talking to your unmanaged code efficiently from Unity using P/Invoke

Quick and Easy: Alter Your Pre-Built Unity Texture Maps using Krita.