Alright, so I’m working on a 2D game, and I used the script below, which I just copy and pasted from some website, to make NPCs patrol between points randomly. And it worked perfectly for a while. And now, suddenly, it’s giving me a bunch of errors about how there’s no NavMeshAgent attached to the asset the script is on, and when I do put an agent on the asset, I get the error saying that the asset needs to be put on a NavMesh, which I have since realized you cannot do in 2D. I do not want a solution that’s just to use 3D with an orthographic camera. I much prefer just using 2D, and this script has worked in the past in 2D, but now it’s just not. If you need to know, I’m in 2020.3.19f1, and that never changed in the project. I also did not change anything drastic that could have caused this error to start, I only placed a few prefabs that had nothing to do with this.
// Patrol.cs
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
public class Patrol : MonoBehaviour {
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
void Start () {
agent = GetComponent<NavMeshAgent>();
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
GotoNextPoint();
}
void GotoNextPoint() {
// Returns if no points have been set up
if (points.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Length;
}
void Update () {
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && agent.remainingDistance < 0.5f)
GotoNextPoint();
}
}