- Home /
Changing a NavMesh Destination
I have a nav mesh on my enemy, I would like the enemy to choose a point, walk to that destination, wait 5 seconds and then choose a new destination. This works once, but when the enemy is due to choose a new location, it chooses a new destination every frame resulting in him moving all around the map very quickly. What changes should I make to get the enemy to choose a new location only once?
void Update ()
{
StartCoroutine(PathRemaining());
}
void WalkPosition()
{
Vector3 randomDirection = Random.insideUnitSphere * 15.0f;
randomDirection += transform.position;
NavMeshHit hit;
NavMesh.SamplePosition(randomDirection, out hit, 15.0f, 1);
Vector3 finalPosition = hit.position;
agent.SetDestination(finalPosition);
Debug.Log(finalPosition);
}
IEnumerator PathRemaining()
{
if (!agent.pathPending)
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
{
animate.SetBool("Idle", true);
//Debug.Log("Done");
yield return new WaitForSeconds(5.0f);
WalkPosition();
}
}
else
{
//Debug.Log("Walking");
animate.SetBool("Idle", false);
}
}
}
Answer by JayFitz91 · Aug 13, 2015 at 01:45 PM
Manage to solve it, I was coming at it completely wrong, I should have been using InvokeRepeating which makes a lot more sense now that I have it implemented ha. Anyway here's the code for anyone else that might need it:
void Start ()
{
animate = GetComponent<Animator>();
agent = GetComponent<NavMeshAgent>();
InvokeRepeating("WalkPosition", 0.0f, 5.0f);
}
// Update is called once per frame
void Update ()
{
PathRemaining();
}
void WalkPosition()
{
Vector3 randomDirection = Random.insideUnitSphere * 15.0f;
randomDirection += transform.position;
NavMeshHit hit;
NavMesh.SamplePosition(randomDirection, out hit, 15.0f, 1);
Vector3 finalPosition = hit.position;
agent.SetDestination(finalPosition);
}
void PathRemaining()
{
if (!agent.pathPending)
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
{
animate.SetBool("Idle", true);
}
}
else
{
animate.SetBool("Idle", false);
}
}
}
Your answer
Follow this Question
Related Questions
How do I stop NavMeshAgents fighting over their exact destination? 0 Answers
how can I set the destination of the nav mesh for multiple objects 2 Answers
Navmeshagent Spins on the Spot when Close to Destination 3 Answers
How to send a signal when a runtime navmesh is created? 0 Answers
Navmesh Agent Rotation at Destination 0 Answers