How to do it...

We will create a component that is able to see enemies nearby:

  1. Create the Visor component, declaring its member variables. It is important to add the following corresponding tags to Unity's configuration:
using UnityEngine; 
using System.Collections; 
 
public class Visor : MonoBehaviour 
{ 
    public string tagWall = "Wall"; 
    public string tagTarget = "Enemy"; 
    public GameObject agent; 
} 
  1. Implement the function for initializing the game object in case the component is already assigned to it:
void Start() 
{ 
    if (agent == null) 
        agent = gameObject; 
}
  1. Declare the function for checking collisions in every frame:
public void OnTriggerStay(Collider coll) 
{ 
    // next steps here 
} 
  1. Discard the collision if it is not a target:
string tag ...

Get Unity 2018 Artificial Intelligence Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.