出现 XXX can only be called on an active agent that has been placed on a NavMesh 的原因及解决方法

错误

“IsStopped” can only be called on an active agent that has been placed on a NavMesh.


“GetRemainingDistance” can only be called on an active agent that has been placed on a NavMesh.

或者其他类似的,由于没有把NavMeshAgent放置在NavMesh所导致的错误

原因

大部分原因是两种

  • 初始化时候放置的NavMeshAgent的Position比NavMesh要低.

比如像我自己的项目,就出现这种情况. 我的NavMesh最后Bake完所在的平面是(0,0.2f,0) 也就是 y = 0.2f 的平面. 但是我创建NavMeshAgent时候,其在Prefab中默认的坐标是(0,0,0)

  • Agent之前在NavMesh上面.但是后面通过设置transfrom.position导致其偏离的NavMesh.

以上两种情况都会出现 如下的错误信息

XXX can only be called on an active agent that has been placed on a NavMesh

解决方法

  • 初始化时候就设置Position偏移
1
2
3
var Prefab ;
var offsetV3 = new Vector(0,0.21f,0);
var newGo = GameObject.Instantiate(Prefab, offsetV3, Quaternion.identity);
  • 使用Wrap函数
1
2
3
4
5
var Prefab;
var offsetV3 = new Vector(0,0.21f,0);
var newGo = GameObject.Instantiate(Prefab);
var agent = newGo.GetComponent<NavMeshAgent>();
agent.Wrap(offsetV3);
坚持原创技术分享,您的支持将鼓励我继续创作!