Unity3D: How to let your A.I. See!

There are many ways to let your A.I. see. I’ll go through the easiest way to do so!

Objective

We want our agent to detect the player when in front. If the player is detected, we then want to enable the “Game Over” cutscene.

Trigger Collider

There are many ways to go about this. The easiest way is to use a trigger collider!

Trigger Colliders is a collision detection system without physics. It enables objects to pass through a game object.

To detect a collision, a rigidbody component must be present on either game object. The player and the guards are already set up. The player has a rigidbody, and the guards do not.

Trigger Collider Setup

Under your agent, create a 3d cube.

Rename it to “Eyes.”

Disable the Mesh Renderer component in the inspector. Enable “Is Trigger” in the Box Collider component.

We then need to adjust the box collider to a proper size and length for which the agent can detect the player.

We can adjust the box collider either in the inspector or in the Scene View.

Let them have eyes!

Next, let’s create a script called “Eyes.”

Drag the script or add the component to the “Eyes” game object.

In this case, I selected the “Eyes” game object and added the script by clicking on “Add Component” in the inspector.

We want the trigger collider in the eyes game object to detect the player. So we’ll use a OnTriggerEnter(Collider other) function. It is called when an object, the player in this setup, passes through (collides) with the agent's trigger collider (Eye’s game object).

using UnityEngine;

public class Eyes : MonoBehaviour
{

private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player Detected");
}
}
}

So if the other game object has the “Player” tag, then let's call a message in Unity. We can see that it is working in Unity’s Console window.

Conclusion

That is all! We can now add logic to enable the game over cutscene when detected!

using UnityEngine;

public class Eyes : MonoBehaviour
{
[SerializeField] private GameObject _gameOver = null;

private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player Detected");
_gameOver.SetActive(true);
}
}
}

Thank you for your time!

Gabriel

--

--

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