Setting a destination

Now that we've set up our AI agent, we need a way to tell it where to go. Our sample project provides a script named Target.cs that does just that.

This is a simple class that does three things:

  • Shoots a ray from the camera origin to the mouse world position using a ray
  • Updates the marker position
  • Updates the destination property of all the NavMesh agents

The code is fairly straightforward. The entire class looks like this:

using UnityEngine;using UnityEngine.AI;public class Target : MonoBehaviour{    private NavMeshAgent[] navAgents;    public Transform targetMarker;    private void Start ()    {      navAgents = FindObjectsOfType(typeof(NavMeshAgent)) as NavMeshAgent[];    }    private void UpdateTargets ( Vector3 targetPosition )    {

Get Unity 2017 Game AI Programming - Third 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.