Gents - I have a Navmesh Agent roaming around a map. When the player approaches within a certain distance from the agent, the agent goes into a “suspicious” mode and pauses for 3 seconds. Within that 3-second window, if the player goes outside the bound, then the agent moves on. Otherwise, the agent comes after the player.
Here’s the corresponding code:
void Update() {
distanceToPlayer = CheckDistance(); // simply returning distance between the agent & player
if (distanceToPlayer < suspicionDistance) {
agent.Stop(); // make agent appear to be thinking...
feelingSuspicious = true;
StartCoroutine(ResolveSuspicion(3.0f)); // make agent stand still for 3 seconds until next move
if (chasingPlayer) {
agent.destination = player.transform.position; // get the intruder!
} else {
agent.Resume(); // hmm, must've been a rat...
}
....
}
....
}
IEnumerator ResolveSuspicion(float duration) {
yield return new WaitForSeconds(duration);
float distanceToPlayer = CheckDistance();
if (distanceToPlayer < suspicionDistance) {
chasingPlayer = true;
}
}
Everything works as intended, except the agent is supposed to pause for 3 seconds as soon as the player steps inside the ‘suspicionDistance’ but it doesn’t – it just comes straight to the player without a pause. I double checked the values for the various distance variables and they are all correct.
I’m thinking I must be misusing the WaitForSeconds method, but can’t seem to figure out how to go about making it work.
===== (UPDATE) =====
For anyone who’s interested, here’s my solution that seems to work:
IEnumerator ResolveSuspicion(float duration) {
agent.Stop();
feelingSuspicious = true;
yield return new WaitForSeconds(duration);
float distanceToPlayer = CheckDistance();
if (distanceToPlayer < suspicionDistance) {
chasingPlayer = true;
} else {
agent.Resume();
}
}
void Update() {
distanceToPlayer = CheckDistance();
if (distanceToPlayer < suspicionDistance) {
if (!chasingPlayer) {
StartCoroutine(ResolveSuspicion(3.0f));
} else {
agent.destination = player.transform.position;
agent.Resume();
}
....
} else {
if (feelingSuspicious) {
feelingSuspicious = false;
agent.Resume();
}
}
}