- Home /
Destination of NavMeshAgent is not updated if the destination is a moving trasform.
Hello. It's the first project I work with NavMesh. I have the following problem: If I set the destination of a NavMeshAgent to a movable transform (for example the player), the NMA will not update its path as the target transform moves around, and it will first get to the destination it had when SetDestination() was called, and then update its destination to be the new point where the moving transform is. I don't want this behavior, instead I'd like a gameobject with a NavMeshAgent to be updating the destination (in real time) to be following something else.
How can I do that ?
Answer by FortisVenaliter · Oct 05, 2017 at 07:39 PM
By updating the NavMeshAgent's destination on a regular basis... say, every second. You don't want to do it too often, because it has to generate a new path every time.
Yup! Thank you very much! That was a part of the problem, and probably the most important. I would never guess that I had to place SetDestination() in some kind of a coroutine with WaitForSeconds() to make it work properly. I think this is some important enough piece of information to be included in the Documentation.
Answer by YoucefB · Oct 05, 2017 at 08:14 PM
You can check if the target has changed its position then update the path if so, using Transform.hasChanged
Exemple
NavMeshAgent agent;
public Transform target;
void Update(){
if (target.hasChanged) {
agent.SetDestination (target.position);
target.hasChanged = false;
}
}
Note that Transform.hasChanged will be called even if the target changed its rotation or scale, so you might want to use this instead:
NavMeshAgent agent;
public Transform target;
Vector3 targetOldPosition = Vector3.zero;
public float checkEvery = 1; // check every one second
float time;
void Update(){
time += Time.deltaTime;
if (time >= checkEvery) {
if (target.position != targetOldPosition) {
agent.SetDestination (target.position);
targetOldPosition = target.position;
}
time = 0;
}
}
Your answer
Follow this Question
Related Questions
A lot of navmesh agents affects ai accuracy 0 Answers
Problem with Navmesh 1 Answer
Problem accessing NavMeshAgent 2 Answers
100+ navmesh agents are not accurate 0 Answers
How to check if my player agent is at the end of the position 2 Answers