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);
}
}
}