- Home /
Question by
zaqmklp · Nov 07, 2019 at 02:22 AM ·
c#unity 5programming
How can I make my navmesh agent stop in between travel to destination points?
Hello!
I'm trying to make my navmesh agent stop after visiting a target location for 2 seconds before moving on to its next target location. Currently, the agent moves to the first location, stops, and doesn't move to the next. Here's my code:
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()
{
//check if agent is at destination
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;
//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;
yield return new WaitForSeconds(time);
execOnce = true;
agent.isStopped = false;
GotoNextPoint();
isCorountineExec = false;
}
}
Comment
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Making Everything Public 0 Answers
Distribute terrain in zones 3 Answers
Build auto id for any object in inspector 1 Answer
Add Special Events for Skills 1 Answer