- Home /
Question by
zaqmklp · Nov 07, 2019 at 02:16 AM ·
c#unity 5programming
How can I make a Navmesh AI pause at its target location before moving on to its next target location
Hello!
I'm trying to use a Navmesh AI to walk to specific locations, pause at them, and then move on. Right now, the agent walks to the first location, pauses, but never resumes. Here's the code for the agent:
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
public class PlayerAgentScript : MonoBehaviour
{
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
private bool isCorountineExec = false;
private bool execOnce = true;
void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.autoBraking = false;
GotoNextPoint();
}
void GotoNextPoint()
{
// Returns if no points have been set up
if (points.Length == 0)
return;
agent.destination = points[destPoint].position;
destPoint = (destPoint + 1) % points.Length;
}
void Update()
{
if (!agent.pathPending && agent.remainingDistance < 5f && execOnce == true)
{
//execOnce is used to ensure the agent will only trigger this if statement once upon arrival at destination
execOnce = false;
Debug.Log("at dest");
//pause for some time, then goto next destination
agent.isStopped = true;
GotoNextLocale(2);
}
}
IEnumerator GotoNextLocale(float time)
{
//isRoutineExec ensures that GotoNextLocale will only execute once (since it's called from update)
if (isCorountineExec)
{
yield break;
}
isCorountineExec = true;
Debug.Log("before wait");
yield return new WaitForSeconds(time);
Debug.Log("after wait");
execOnce = true;
agent.isStopped = false;
GotoNextPoint();
isCorountineExec = false;
}
}
Comment