2

Is there a way to raise a flag on the Navmesh navigation end, or to use a callback when it finish?

I want to run a function when my objection reach to the desire position, I can check on every frame update if the navigation has finished but I want a more elegant and efficient solution.

Thanks.

Ilan12
  • 81
  • 2
  • 11

3 Answers3

0

It depends what you mean by "ends", if you want to know when a path is no longer available for the NavAgent, you can use pathStatus, for example you could write:

if(myNavAgent.pathStatus != NavMeshPathStatus.PathComplete) {
  // Do stuff
}

If you me reaching a location such as a "waypoint" you can use myNavAgent.remainingDistance then check if it is less than a certain value.

Here's the unity NavAgent scriptingAPI doc link: https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.html

If this doesn't work, let me know!

CodingGuy
  • 71
  • 7
0

I have Thought the same question and i couldn't find a callback, However i managed to solve with triggers. For example if my agent goes point a, i put trigger that position and when my agent touches it i stopped agent.

0

If someone will search, then here is my solution:

NavMeshAgent _agent; 
bool _hasPath;

public Action OnPointReached;

void Update()
{
    if (_hasPath)
    {
        if(!_agent.hasPath)
        {
            _agent.isStopped = true; // For understanding - here the agent stops 
            OnPointReached?.Invoke(); // here we start an event or a function
        }
        else
        {
            _agent.isStopped = false; // The agent is moving
        }
    }
}

void LateUpdate()
{
    _hasPath = _agent.hasPath;
}

The bottom line is that you need to duplicate the NavMeshAgent.hasPath value for the first check, but send it late - for this we assign the _hasPath value in LateUpdate. Roughly speaking: the agent will reach the destination, but the check will work again due to the fact that the value has not yet been updated, and inside we transfer the current value directly from the agent and get a single event firing.

shenntaro
  • 1
  • 1