Unity寻路报错“SetDestination“ can only be called on an active agent that has been placed on a NavMesh.

This error indicates that the node where the NavMeshAgent is located is not placed on the pathfinding grid. This error is usually accompanied by

"Failed to create agent because it is not close enough to the NavMesh"类似警告。

It indicates that the creation of the pathfinding agent failed, and the subsequent setting of the destination will definitely lead to failure.

Such problems need to be checked:

  1. Whether NavMeshAgent is enabled when calling SetDestination
  2. Does NavMeshSurface exist?

If everything is set correctly, but still report this error. Congratulations, I have encountered the same problem~

I have never encountered this error in the Editor or the test APK (if I encountered it, I must have figured out a way to solve it~), and when the project was launched, I found that bugly reported a lot of this error. It made me very puzzled. Fortunately, I found the source code of NavMeshAgent and found a slightly safer way to avoid mistakes.

One of the more important functions in Agent pathfinding is the obstacle avoidance function. Unity uses a group detour manager (Detour Crowd Manager) to manage Agent. The premise that we can call SetDestination is that our Agent is added to this bypass manager. There are several ways to trigger adding behavior:

  1. NavMeshSurface changes, such as Obstacle digging holes will trigger this behavior
  2. NavMeshAgent::OnEnable will try to add
  3. Calling NavMeshAgent::Warp will add

The first trigger behavior needs to modify the pathfinding grid, the second is called by the system, and the last one can be triggered by ourselves.

Here you can check if you set the transform where your Agent is located to use transform.position directly?

If so, it is easy to handle, replace the way of modifying the coordinates by transform.position to modify by using agent.Warp.

 In this way, while adding to the detour system, the coordinates of the transform will also be modified.

As for why this happens, I guess it was unsuccessful when adding Detour Crowd for the first time, and there are many reasons for the failure, because it is impossible to debug, so I can only have this kind of guess. Subsequent errors caused by not triggering this adding behavior again. But at least, using Warp to set the coordinates directly can guarantee that there will be no mistakes.

Guess you like

Origin blog.csdn.net/weixin_36719607/article/details/126711102