- Home /
The question is answered, right answer was accepted
[Javascript] Creating waiting points for random movement with NavMesh Script
Hi, Im facing a problem creating waiting points for a NavMesh Script I got on Unity Answers, its pretty much a script just to create random points for the character with NavMeshAgent to move on a NavMesh plane, but problem is that I want the character to pause on every point reached and wait for several seconds before finding a new path and I found out that it is not possible to have a yield on function Update. I tried to add an Idle function after end of path is reached but it doesn't work. I'm new with unity scripting, so I am basically just messing around with the scripts, any ideas on how to make it possible? a solution is much appreciated!
#pragma strict
import System.Collections.Generic;
var navMeshScript : navMesh;
var path : List.<Vector3> = null;
var targetNodeIndex : int = 0;
var targetNode : Vector3;
var idleTime = 2;
function Start () {
//Find the navmesh script in the scene
navMeshScript = GameObject.FindObjectOfType(navMesh).GetComponent("navMesh");
}
function Idle ()
{
// print ("idle");
yield WaitForSeconds(idleTime);
while (true)
{
yield WaitForSeconds(5);
}
}
function Update () {
//If the path is null
if (path == null) {
//Find a new random path
Idle();
path = navMeshScript.findRandomPath(transform.position);
targetNodeIndex = 5;
}
//The end of the path hasn't been reached
if (targetNodeIndex < path.Count) {
targetNode = path[targetNodeIndex];
//If the character is close to the target node
if (Vector3.Distance(transform.position, targetNode) < distanceToNode) {
//Target the next node
targetNodeIndex += 1;
}
}
//The end of the path has been reached
else {
path = null;
}
transform.position += moveSpeed*(targetNode-transform.position).normalized*Time.deltaTime;
transform.LookAt(targetNode);
Idle();
}
Answer by protopop · Feb 05, 2016 at 04:42 PM
put the yield inside a separate function and call that function from your update loop
function newPatrol(){
yield WaitForSeconds(5.0);
findNewPathOrWhatever();
}
Follow this Question
Related Questions
Problem with yield waitForSeconds in for loop 0 Answers
NavMesh area, walkable but not accessible. 2 Answers
NavMeshAgent and NavMeshObstacle together, unit jumping a small distance on toggle 2 Answers
Is there a limit on how far a navmesh agent can go? 0 Answers
Navmesh on all sides of an object? 0 Answers