其他分享
首页 > 其他分享> > NavMeshAgent.SetDestination后不会自动寻路问题

NavMeshAgent.SetDestination后不会自动寻路问题

作者:互联网

# 下面的代码是想实现点击鼠标左键,寻路到指定的位置;但是运行后,并不会寻路,而是立即打印了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;
        }
    }
}

 

标签:navMeshAgent,true,enabled,SetDestination,Input,NavMeshAgent,寻路
来源: https://www.cnblogs.com/sailJs/p/16412490.html