# 下面的代码是想实现点击鼠标左键,寻路到指定的位置;但是运行后,并不会寻路,而是立即打印了end
void Update() { if (Input.GetMouseButtonUp(1)) { _navMeshAgent.enabled = true; _navMeshAgent.SetDestination(_targetPos); } if (_navMeshAgent.enabled) { if (_navMeshAgent.remainingDistance <= 0) { Debug.Log($"end"); _navMeshAgent.enabled = false; } } }
# 经过各种排查之后,最终确定是SetDestination后,会先计算如何寻路,至少要到下一帧才进行真正的寻路,所以方法1是SetDestination后return等待一帧
void Update() { if (Input.GetMouseButtonUp(1)) { _navMeshAgent.enabled = true; _navMeshAgent.SetDestination(_targetPos); return; } if (_navMeshAgent.enabled) { if (_navMeshAgent.remainingDistance <= 0) { Debug.Log($"end"); _navMeshAgent.enabled = false; } } }
# 或者方法2判断下是否在计算寻路数据中
void Update() { if (Input.GetMouseButtonUp(1)) { _navMeshAgent.enabled = true _navMeshAgent.SetDestination(_targetPos) } if (_navMeshAgent.enabled && !_navMeshAgent.pathPending) { if (_navMeshAgent.remainingDistance <= 0) { Debug.Log($"end"); _navMeshAgent.enabled = false; } } }